【问题标题】:Issue with scala object companion and traitscala对象伴侣和特征的问题
【发布时间】:2020-05-09 20:25:20
【问题描述】:

我试图在 scala 中做这样的事情,以便 Category 类通过参数接收其属性,但我收到以下错误:

object creation impossible, since method apply in trait ModelCompanion of type => asd.Category is not defined
  object Category extends ModelCompanion[Category] {
         ^
one error found

代码在这里:

object asd {

  trait ModelCompanion[M <: Model[M]] {
    def apply: M
  }

  trait Model[M <: Model[M]] {
    var id: Int = 0
  }

  object Category extends ModelCompanion[Category] {
    def apply(name: String): Category = new Category(name)
  }

  class Category(var name: String) extends Model[Category] {
  // Do something with name
  }

}

我是 scala 的新手,所以如果您能给我一些指导,我将不胜感激。

【问题讨论】:

    标签: scala class object traits


    【解决方案1】:

    ModelCompanion 定义了一个没有任何参数(或参数列表)的抽象方法apply。在Category 中,您定义了一个apply 方法,该方法采用String 类型的参数。这不是抽象方法的实现,因为它不接受相同数量和类型的参数。因此Category 没有提供ModelCompanion 的抽象apply 方法的合适定义,因此无法实例化。

    根据您想要的行为,您应该将 ModelCompanion.apply 的定义更改为 def apply(name: String): M 或引入另一个类型参数并将其用作参数类型。

    【讨论】:

      【解决方案2】:

      很快:

      def apply:M
      //and 
      def apply(name:String):M
      //are not the same methods
      
      //if you try define it with override modifier
      override def apply(name: String): Category = new Category(name)
      
      //it will expose this fact to you with error:
      //method apply overrides nothing.
      //Note: the super classes of object Category 
      //      contain the following, non final members named apply:
      //def apply: ammonite.$sess.cmd8.asd.Category
      
      //You need to define `ModelCompanion` with appriopriate `apply`
      
      trait ModelCompanion[M <: Model[M]] {
        def apply(name:String): M
      }
      
      // or override properly current (argumentless) one  
      object Category extends ModelCompanion[Category] { 
        override def apply: Category = new Category("Category" + Random.nextInt())
      }
      
      
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-22
        • 2015-07-20
        • 2020-06-18
        • 1970-01-01
        • 1970-01-01
        • 2015-06-21
        相关资源
        最近更新 更多