Private and protected constructor in Scala

我一直很好奇在 Scala 中没有一个显式的主构造函数,只有类主体的内容的影响。

In particular, I suspect that the private or protected constructor pattern, that is, controlling construction through the companion object or another class or object's methods might not have an obvious implementation.

我错了吗? 如果错了,怎么做到的?

35979 次浏览

You can declare the default constructor as private/protected by inserting the appropriate keyword between the class name and the parameter list, like this:

class Foo private () {
/* class body goes here... */
}

亚历山大的回答是正确的,但 Scala 编程提供了另一种选择:

sealed trait Foo {
// interface
}


object Foo {
def apply(...): Foo = // public constructor


private class FooImpl(...) extends Foo { ... } // real class
}