【发布时间】:2015-07-17 08:28:20
【问题描述】:
我很好奇 Scala 中最好的解决方案是什么:
class MyClass private (x: Any, y: Int) {
def this(x: Int, y: Int) = this(x, y)
def this(x: String, y: Int) = this(x, y)
}
val x0 = new MyClass(1, 1)
val x1 = new MyClass("1", 1)
//val x2 = new MyClass(1.0, 1) // Correctly doesn't typecheck
下面的错误对我来说没有多大意义,因为似乎在辅助构造函数之前定义了一个可行的构造函数:
Error:(3, 31) called constructor's definition must precede calling constructor's definition
def this(x: Int, y: Int) = this(x, y)
^
关于更多上下文,我实际上是在尝试处理 Scala.js 中的 JavaScript API,其函数采用的参数可以是 String 或 js.Object,但我认为这说明了这个问题。
【问题讨论】: