在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,其函数可以是Stringjs.Object的参数,但我认为这体现了问题。

明确地将类型归为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-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

相关内容

最新更新