I have two traits
trait AppModel {}
trait ModelOperations {
def get(model: AppModel): Option[AppModel]
def create(model: AppModel): Boolean
}
And implemented classes
class User extends AppModel {
val id = "xyz"
val name = "abc"
}
class UserOperations extends ModelOperations {
override def get(user: User) : Option[User] = {
// get a new user object by filtering existing parameters
return None
}
override def create(user: User): Boolean = {
// do something
return false
}
}
However when I try to compile, I get method get overrides nothing
and method create overrides nothing
errors
What I intent to do is: declare an interface I
with methods that will accept parameters of any class T
that extends AppModel
and return T
And any class that extends I
can have methods that accept exactly class T
as parameters (and not any other class R
of AppModel
)
How do I go about this ?
Try this
trait AppModel {}
trait ModelOperations {
def get[T<:AppModel](model: T): Option[T]
def create[T<:AppModel](model: T): Boolean
}
class User extends AppModel { val id = "xyz" val name = "abc" }
class UserOperations extends ModelOperations { override def get[User](user: User) : Option[User] = { // get a new user object by filtering existing parameters return None } override def create[User](user: User): Boolean = { // do something return false } }
You can use a type
field with a bound, that you can refine in the concrete implementation. Here's an example
trait AppModel
trait ModelOperations {
type T <: AppModel
def get(model: T): Option[T]
}
class User extends AppModel
class UserOperations extends ModelOperations {
type T = User
def get(user: User): Option[User] = None
}
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.