Is it "cleaner" (resp. better performance) to declare methods in the case class or companion object?
e.g.
case class My(a:A) {
def m(args) = {...}
}
or
object My {
def m(m:My, args) = {...}
}
case classes automatically have equality and nice toString methods based on the constructor arguments. case classes can have methods just like normal classes.
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 = ??? }
When you want to define some functionality related to a case class you have two possible ways to do this. The first one is to create functions directly in the case class. Note that in order to define a companion object for a class you have to set the same names for them and declare them in the same file.
A companion object's apply method lets you create new instances of a class without using the new keyword. A companion object's unapply method lets you de-construct an instance of a class into its individual components.
I would prefer to put methods in case class. Putting it in companion object sounds like Anemic Domain Model anti-pattern AnemicDomainModel.
Moreover you can override case class methods later or extend and mix some traits.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With