Scala 2.9 中限制类构造函数的可见性
您好,
如何使 Foo 构造函数仅对此包(单元测试+伴随对象)可见?
我不想在这 2 个文件之外实例化 Foo...
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"
}
}
}
我正在使用 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 files...
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个:
那么
Foo
的构造函数只能从foo
包中访问。您可以在此处阅读有关 Scala 可见性的更多信息(特别是范围内私有和范围内受保护)< /a>.
Try this:
Then the constructor of
Foo
is only accessible from thefoo
package.You can read more about Scala's visibility (look especially for scoped private and scoped protected) here.