How to use Companion Object In Scala

Below is the Scala program to access a case class method from another class using a companion object:

Scala
case class Person(name: String) {
  def greet(): Unit = println(s"Hello, $name")
};

object AnotherClass {
  def main(args: Array[String]): Unit = {
    val person = Person("Alice");
    person.greet()
  }
};

Output
Hello, Alice

Explanation:

  1. We define a case class Person with a method greet() that prints a greeting message.
  2. In the AnotherClass object, we create an instance of Person and invoke the greet() method.

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

Similar Reads

Using Companion Object

Below is the Scala program to access a case class method from another class using a companion object:...

Using Inheritance

Below is the Scala program to access a case class method from another class using inheritance:...

Using Implicit Conversion

Below is the Scala program to access a case class method from another class using implicit conversion:...

Conclusion

Accessing a case class method from another class in Scala can be accomplished using various techniques, such as companion objects, inheritance, or implicit conversions....

Contact Us