How to use Implicit Conversion In Scala
Below is the Scala program to access a case class method from another class using implicit conversion:
object Main {
def main(args: Array[String]): Unit = {
import AnotherClass._;
val person = Person("Charlie");
person.invokeGreet();
}
};
case class Person(name: String) {
def greet(): Unit = println(s"Hello, $name");
};
object AnotherClass {
implicit class PersonOps(person: Person) {
def invokeGreet(): Unit = person.greet();
}
};
Output
Hello, Charlie
Explanation:
- We define a case class
Person
with a methodgreet()
. - In the
AnotherClass
object, we define an implicit classPersonOps
that adds a methodinvokeGreet()
toPerson
. - In the
Main
object, we import the implicit conversion and use it to invoke theinvokeGreet()
method on aPerson
instance.
How to Access a Case Class Method from Another Class in Scala?
Accessing a case class method from another class in Scala can be achieved through several approaches. Case classes are commonly used to model immutable data and provide convenient methods for accessing and manipulating data fields. The article focuses on discussing different methods to access a case class method from another class in Scala.
Table of Content
- Using Companion Object
- Using Inheritance
- Using Implicit Conversion
- Conclusion
Contact Us