Restrict class constructor visibility in Scala 2.9
Greetings,
How can I make the Foo constructor visible only to this package (unit test + companion object) ?
I don't want to be able to instantiate Foo outside of this 2 fil开发者_运维技巧es...
Foo.scala
package project.foo
class Foo(val value: String)
object Foo {
def generate: Foo = new Foo("test")
}
FooSpec.scala
package project.foo
import org.spec2.mutable._
class FooSpec extends Specification {
"Foo" should {
"be constructed with a string" {
val foo = new Foo("test")
foo.value must be "test"
}
}
}
I'm using Scala 2.9
Try this:
package project.foo
class Foo private[foo] (value: String)
Then the constructor of Foo
is only accessible from the foo
package.
You can read more about Scala's visibility (look especially for scoped private and scoped protected) here.
精彩评论