2017-03-20 7 views
3

case classの場合はコンパイラによって自動的にコンパニオンオブジェクトが生成されます。ケースクラスの定義オブジェクト

case class Clas(i: Int) 

しかし、私の場合は私が便宜上、いくつかのfatory方法apply(s: String): Clasを追加します。したがって、自分自身をオブジェクトとして定義しました:

object Clas { 
    def apply(s: String) = //create Clas 
} 

どのように動作しますか?コンパイラが生成したオブジェクトのメソッドがまだ利用可能なのはなぜですか?

答えて

4

コンパイラはコンパニオンオブジェクトにおける合成のものを使用してメソッドをマージ:

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

case class Clas(i: Int) 
object Clas { def apply(s: String): Clas = null } 

// Exiting paste mode, now interpreting. 

defined class Clas 
defined object Clas 

scala> Clas.apply _ 
<console>:13: error: ambiguous reference to overloaded definition, 
both method apply in object Clas of type (i: Int)Clas 
and method apply in object Clas of type (s: String)Clas 
match expected type ? 
     Clas.apply _ 
      ^
+0

非常にシンプルな、おかげで多くの。 –

関連する問題