在 Scala 中使用多态参数重载私有构造函数
Overload private constructor with polymorphic arguments in Scala
我很好奇在 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
或 [=13] =],但我认为这说明了这个问题。
我从未使用过 Scala-js,但这能解决您的问题吗:
class MyClass private (x: Any, y: Int)
object MyClass{
def apply(x:Int,y:Int) = new MyClass(x,y)
def apply(x:String, y:Int) = new MyClass(x,y)
}
val x0 = MyClass(1, 1)
val x1 = MyClass("1", 1)
//val x2 = new MyClass(1.0, 1) // Correctly doesn't typecheck
将类型明确指定为 Any
将有助于:
class MyClass private (x: Any, y: Int) {
def this(x: Int, y: Int) = this(x: Any, y)
def this(x: String, y: Int) = this(x: Any, y)
}
在你的例子中,构造函数会递归地调用自己,这显然是荒谬的。
我很好奇在 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
或 [=13] =],但我认为这说明了这个问题。
我从未使用过 Scala-js,但这能解决您的问题吗:
class MyClass private (x: Any, y: Int)
object MyClass{
def apply(x:Int,y:Int) = new MyClass(x,y)
def apply(x:String, y:Int) = new MyClass(x,y)
}
val x0 = MyClass(1, 1)
val x1 = MyClass("1", 1)
//val x2 = new MyClass(1.0, 1) // Correctly doesn't typecheck
将类型明确指定为 Any
将有助于:
class MyClass private (x: Any, y: Int) {
def this(x: Int, y: Int) = this(x: Any, y)
def this(x: String, y: Int) = this(x: Any, y)
}
在你的例子中,构造函数会递归地调用自己,这显然是荒谬的。