据我所知,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 _
^
关于scala - 为案例类定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42901402/