2017-01-02 46 views
1

我有以下代碼:斯卡拉案例類和同伴對象不能覆蓋使用DIFF簽名應用於

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

回答

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 

但是,這引起混淆,我不會用那個。

+0

爲什麼這個錯誤不是早期修復的,它看起來像一個嚴重的缺陷? – pacman

+0

@pacman它根本沒有優先。請注意,您可以部分解決該問題,查看我的更新。 –