我試過將建構式設為私有,如下所示:
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$
我想強制呼叫者使用智能建構式來防止實體化無效的列舉并限制介紹表單的數量。
uj5u.com熱心網友回復:
只需將類名添加到 private 以限制范圍:
enum X {
case Stuff private[X] (value: Int)
}
object X {
def stuff(s: String) =
X.Stuff(s.toInt)
}
示例作業代碼:https : //scastie.scala-lang.org/hUPECAJFSzqAus6c5slBHQ
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/358550.html
