Scala对象同伴和特征的问题。

问题描述 投票:0回答:1

我试图在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个回答
1
投票

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

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


1
投票

短时间内。

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())
}



© www.soinside.com 2019 - 2024. All rights reserved.