How to add a method to an case class instance?

Hey Guys,

Is it possible to define methods for a case class instance? I know I can define class methods using the companion object but I’m not loving this invocation style:

MyCaseClass.myFunc( case_class_instance )

I would prefer to be able to do this:

case_class_instnace.myFunc

Any direction would be appreciated.

Adding method to a case class is mostly the same as adding method to non-case class. So you can write:

case class MyCaseClass(cParam1: Int, cParam2: String) {
  def myFunc: Sting = ???
}
3 Likes

Awesome! Thanks for prompt and concise answer.

Just to add to @tarsa’s answer, you can use implicits to add functionality to any class without having to change the code in the class (add hoc polymorphism). Example

 case class MyCaseClass(someInt : Int)

 implicit class MyCaseClassOps(instOf : MyCaseClass) {
  def myFunc : Int = 1
 }

 val myCaseClassObj = MyCaseClass(someInt = 1)
 
//Now you can call the method myFunc as if it were directly defined inside the case class 
 myCaseClassObj.myFunc

 println(s"Printing myCaseClassObj.myFunc = ${myCaseClassObj.myFunc}")
1 Like