Reputation: 9771
Is it worth, to control the visibility of case class that represent value object ? If so, is a visibility modifier on the case class enough, or using an explicit companion object, and a private constructor, would be better ?
Version 1:
case class MyClass private/protected/private[] {}
Version 2:
case class MyClass private
object MyClass {
def apply = {
new MyClass
}
}
In sum, the question could be summarize as how to deal with value object in scala. I personally want to enforce the no new, so that is i want to change something in the creation of the object, I can do it at any time. That is, by simply adding a companion object when necessary.
Upvotes: 1
Views: 421
Reputation: 167921
A visibility modifier on the case class constructor does not propagate to the companion object, so creating one yourself by hand with the exact same apply method is unnecessary.
You can verify this yourself trivially:
$ scala
Welcome to Scala version 2.11.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_37).
Type in expressions to have them evaluated.
Type :help for more information.
scala> case class X private () {}
defined class X
scala> new X
<console>:10: error: constructor X in class X cannot be accessed in object $iw
new X
^
scala> X()
res1: X = X()
Note that just plain X
is the name of the companion object. You can't get a new X
by naming the companion object; that won't call its apply method even if a no-argument apply exists. So you can't omit the empty parameter list ()
.
The above is all true in the REPL, but compiled code fails.
Upvotes: 3