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:
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.
ModelCompanion
defines an abstract method apply
without any arguments (or argument lists). In Category
you define an apply
method that takes an argument of type String
. That's not an implementation of the abstract method because it doesn't accept the same number and types of arguments. Therefore Category
does not provide a suitable definition of ModelCompanion
's abstract apply
method and therefore can not be instantiated.
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.
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())
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.