开发者

Restrict class constructor visibility in Scala 2.9

开发者 https://www.devze.com 2023-03-06 19:07 出处:网络
Greetings, How can I make the Foo constructor visible only to this package (unit test + companion object) ?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号