Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala case class put methods in companion object?

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) = {...}
}
like image 667
cedricbastin Avatar asked Dec 29 '14 20:12

cedricbastin


People also ask

Can Scala case class have methods?

case classes automatically have equality and nice toString methods based on the constructor arguments. case classes can have methods just like normal classes.

How do you add methods to a case class?

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 = ??? }

Can case class have companion object?

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.

Which operations are provided by collection companion object in Scala?

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.


1 Answers

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.

like image 116
Przemek Avatar answered Sep 20 '22 18:09

Przemek