Scala案例类和伴随对象不能覆盖应用diff签名

时间:2017-01-02 16:00:17

标签: scala

我有以下代码:

case class Foo(x:Int) {
  def this(x: Int, y: Int) = this(x + y)
}

object Foo {
  def apply(x: Int, y: Int) = new Foo(x, y)
}

我收到了编译错误:Error:Person is already defined as (compiler-generated) case class companion object Person 由于apply具有另一个签名这一事实,此代码必须有效。也许它是scala中的一个bug,我的scala版本是2.11.8

1 个答案:

答案 0 :(得分:2)

这是一个开放的错误(SI-3772)。应该在Scala 2.12.2(here is the pull request which fixes it)中修复。

如果您首先在范围中定义object,然后您的this(x, y)构造函数将隐藏同伴apply方法,则可以解决此问题:

scala> :pa
// Entering paste mode (ctrl-D to finish)

object Foo {
  def apply(x: Int, y: Int): Foo = {
    println("in new apply")
    new Foo(x, y)
  }
}

case class Foo(x: Int) {
  def this(x:Int, y:Int) = this(x+y)
}

Foo(1,1)

// Exiting paste mode, now interpreting.

in new apply

但这会造成歧义,我不会使用它。

相关问题