在Scala中使用多态参数重载私有构造函数

时间:2015-07-16 23:24:56

标签: scala scala.js

我很好奇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)
                         ^

对于更多上下文,我实际上是尝试使用带有Stringjs.Object参数的函数来处理Scala.js中的JavaScript API,但我认为这是一个例证。这个问题。

2 个答案:

答案 0 :(得分:2)

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

在你的情况下,构造函数会递归地调用它们,这显然是荒谬的。

答案 1 :(得分:1)

我从未使用过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