为案例 class 定义对象

Defining object for case class

据我所知,case class 伴随对象是由编译器自动生成的。

case class Clas(i: Int)

但在我的例子中,为了方便起见,我想添加一些 fatory 方法 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 _
            ^