我一直很好奇Scala中没有明确的主要构造函数的影响,只是类体的内容.
特别是,我怀疑私有或受保护的构造函数模式,即通过伴随对象或另一个类或对象的方法控制构造可能没有明显的实现.
我错了吗?如果是这样,它是如何完成的?
Ale*_*tec 186
您可以通过在类名和参数列表之间插入适当的关键字将默认构造函数声明为private/protected,如下所示:
class Foo private () {
/* class body goes here... */
}
Run Code Online (Sandbox Code Playgroud)
Dan*_*ral 64
Aleksander的回答是正确的,但Scala中的Programming提供了另一种选择:
sealed trait Foo {
// interface
}
object Foo {
def apply(...): Foo = // public constructor
private class FooImpl(...) extends Foo { ... } // real class
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33236 次 |
| 最近记录: |