Let's say I have the following trait
trait Foo[T] {
def overrideMe(other:Foo[T]) : Int
}
I would like to be able to do
class Bar extends Foo[Int] {
override def overrideMe(other:Bar) : Int = other.BarFn
}
but it does not compile. The reason is that I would like overrideMe to be able to use functionality of the subtype. I could do something like
class Bar extends Foo[Int] {
override def overrideMe(other:Foo[Int]) : Int = {
other.asInstanceOf[Bar].BarFn
}
but that doesn't look very nice.
Is it possible to say in the trait that the virtual funcation can be overridden with a subtype?
edit @agilesteel That almost works, but I run into trouble if I have a function in another class relying only on the trait Foo
class Test[T] {
def callOverrideMe(a : Foo[T], b : Foo[T] ) : Int = a.overrideMe(b)
}
I get a compile error: type mismatch; found b.type (with underlying type foo.Foo[T]) required a.SubType
Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.
Classes and objects can extend traits, but traits cannot be instantiated and therefore have no parameters.
Only classes can be extended. Traits are not classes. They can be used/included by classes but are not classes themselves.
Unlike traits in Scala, traits in PHP can have a constructor but it must be declared public (an error will be thrown if is private or protected). Anyway, be cautious when using constructors in traits, though, because it may lead to unintended collisions in the composing classes.
trait Foo[T] {
type TheSubType <: Foo[T]
def overrideMe(other: TheSubType) : Int
}
class Bar extends Foo[Int] {
type TheSubType = Bar
override def overrideMe(other: Bar) : Int = other.barFn
def barFn = 10
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With