我可以将主构造函数设为私有,同时在Scala中保持辅助构造函数公开吗?

Iva*_*van 20 constructor scala

因为我打算只重载构造函数以供公共使用来创建类实例,所以我想将主构造函数设为私有.这可能在Scala中吗?

Nic*_*las 25

是的你可以:

class A private (x: Int) {
  def this() = this(42)
}
Run Code Online (Sandbox Code Playgroud)

  • 您还可以从伴随对象中调用私有主构造函数; 对工厂方法有用. (7认同)

And*_*yle 5

是 - 您可以通过在类名后指定修饰符来确定主构造函数的可见性,例如:

class Foo private (a: Int, b: String) {
   // ...
}
Run Code Online (Sandbox Code Playgroud)

当然,辅助构造函数仍然(实际上必须)引用此主构造函数,同时仍然被声明为public.