您如何定义只能由其伴随对象创建的枚举? (想想聪明的构造函数)

How do you define an enum that can only be created by its companion object? (think smart constructors)

我试过将构造函数设为私有,如下所示:

enum X {
  case Stuff private (value: Int)
}

object X {
  def stuff(s: String) = 
    X.Stuff(performSomeValidationAndCalculation(s))
}

但它抱怨:

method apply cannot be accessed as a member of Playground.X.Stuff.type from module class X$

我想强制调用者使用智能构造函数来防止无效枚举被实例化并限制引入形式的数量。

只需将class名称添加到私有以限制范围:

enum X {
  case Stuff private[X] (value: Int)
}

object X {
  def stuff(s: String) = 
    X.Stuff(s.toInt)
}

示例工作代码:https://scastie.scala-lang.org/hUPECAJFSzqAus6c5slBHQ