I have a trait with a size comparison function that I want to implement in a sublcass:
trait A {
def isLessThan(that: A): Boolean
...
}
class SubOfA() extends A {
...
override def isLessThan(that: SubOfA): Boolean = {
this.size < that.size
}
...
}
However, the method isn't a valid override because the argument type is SubOfA
and not A
.
I've also tried making the argument type this.type
, but then when I am calling the method from an abstract setting I can't use an object of type A
as the argument:
...
(foo: A, bar: A) => foo.isLessThan(bar)
This would expect type foo.type
and not A
which are the same but I don't think the compiler knows that yet.
Any ideas of how I could get something like this to work? I've looked all over the place to find an answer to this, but can't find anything. Maybe I don't know what is the right question to ask.
You can fix the first method with:
class SubOfA() extends A {
override def isLessThan(that: A): Boolean = that match {
case that : subOfA => this.size < that.size
case _ => throw new UnsupportedOperationException("Wrong comparison") //or whatever behaviour deemed suitabe here
}
}