[英]Issue with scala object companion and trait
我正在尝试在 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
代码在这里:
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 的新手,所以如果您能给我一些指导,我将不胜感激。
ModelCompanion
定义了一个抽象方法apply
没有任何 arguments(或参数列表)。 在Category
中,您定义了一个接受String
类型参数的apply
方法。 这不是抽象方法的实现,因为它不接受相同数量和类型的 arguments。 因此Category
没有提供ModelCompanion
的抽象apply
方法的合适定义,因此无法实例化。
根据您想要的行为,您应该将ModelCompanion.apply
的定义更改为def apply(name: String): M
或引入另一个类型参数并将其用作参数类型。
不久:
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.