Scala 中的私有和受保护构造函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1730536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 01:44:28  来源:igfitidea点击:

Private and protected constructor in Scala

scala

提问by Don Mackenzie

I've been curious about the impact of not having an explicit primary constructor in Scala, just the contents of the class body.

我一直很好奇在 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.

特别是,我怀疑私有或受保护的构造函数模式,即通过伴随对象或另一个类或对象的方法控制构造可能没有明显的实现。

Am I wrong? If so, how is it done?

我错了吗?如果是这样,它是如何完成的?

回答by Aleksander Kmetec

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... */
}

回答by Daniel C. Sobral

Aleksander's answer is correct, but Programming in Scalaoffers an additional alternative:

Aleksander的回答是正确的,但Programming in Scala提供了另一种选择:

sealed trait Foo {
 // interface
}

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

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