简体   繁体   English

scala object 伴侣和特征的问题

[英]Issue with scala object companion and trait

i am trying to do something like this in scala so that the Category class receives its attributes by parameters but i get the following error:我正在尝试在 scala 中执行类似的操作,以便类别 class 通过参数接收其属性,但我收到以下错误:

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

Code here:代码在这里:

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
  }

}

I am new to scala so if you could give me some guidance on this I would be very grateful.我是 scala 的新手,所以如果您能给我一些指导,我将不胜感激。

ModelCompanion defines an abstract method apply without any arguments (or argument lists). ModelCompanion定义了一个抽象方法apply没有任何 arguments(或参数列表)。 In Category you define an apply method that takes an argument of type String .Category中,您定义了一个接受String类型参数的apply方法。 That's not an implementation of the abstract method because it doesn't accept the same number and types of arguments.这不是抽象方法的实现,因为它不接受相同数量和类型的 arguments。 Therefore Category does not provide a suitable definition of ModelCompanion 's abstract apply method and therefore can not be instantiated.因此Category没有提供ModelCompanion的抽象apply方法的合适定义,因此无法实例化。

Depending on the behavior you want, you should either change the definition of ModelCompanion.apply to def apply(name: String): M or introduce another type argument and use that as the argument type.根据您想要的行为,您应该将ModelCompanion.apply的定义更改为def apply(name: String): M或引入另一个类型参数并将其用作参数类型。

Shortly:不久:

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



声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM