定义案例类的对象



据我所知case class配套对象是由编译器自动生成的。

case class Clas(i: Int)

但就我而言,为了方便起见,我想添加一些apply(s: String): Clas方法。所以将对象定义为:

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

它是如何工作的?为什么编译器生成的对象中的方法仍然可用?

编译器将您的方法与配套对象中的合成方法合并:

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 _
            ^

最新更新