Scala class class input methods in companion object?

Is it "cleaner" (correspondingly better performance) for declaring methods in the case class or companion object?

eg.

case class My(a:A) { def m(args) = {...} } or object My { def m(m:My, args) = {...} } 
+7
scala case-class
source share
2 answers

I would prefer to put methods in the case class. Putting it in a companion object sounds like Anemic Domain Model anti-pattern AnemicDomainModel .

In addition, you can override case class methods later, or extend and mix some features.

+6
source share

Better put the methods in the case class; Isn't that the whole point of classes in general? object is static and is usually a bad place for methods, as this means that they need to take one more argument than otherwise. I would expect the method in the class to work very slightly better, since it will not need to load an instance of the companion object (and, more generally, it is closer to the style that is optimized for the JVM), but this is almost certainly also a small difference in matter in any real program. Of course, no rule is absolute; if you find that a particular method is better suited for a companion object, be sure to put it there.

+5
source share

All Articles