【问题标题】:Defining object for case class为案例类定义对象
【发布时间】:2017-03-20 18:43:36
【问题描述】:

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

case class Clas(i: Int)

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

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

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

【问题讨论】:

    标签: scala case-class


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-05
      • 1970-01-01
      • 2012-05-15
      • 2015-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多