I’m having some issues with inheritance and lower bounds in scala; I’ll try to explain it with an example:
I have a class Person with a signature like:
def doSomething[P<%Person](persons :List[P]) {
}
I’ve also created a child class Worker, and his method doSomething looks like this:
override def doSomething(persons: List[Worker]) {
}
However this fires an error, stating that Worker.doSomething() doesn’t override anything?
You cannot inherit this way. It violates the Liskov Substitution Principle. I’ll show why that is the case. Suppose you could compile these classes:
Now, this simple program would fail:
Since
p2is not aWorker, that call is invalid. However, sincep1is aPerson, that call is valid! This contradiction is a result of the override you propose.But it’s worse than that! This ALSO won’t work:
Now, even though it is passing a list of workers, as expected by
p1, it fails becausedoSomethinginWorkerdoesn’t expect a type parameter. However, the methoddoSomethingofPersondeclared that a type parameter should be passed! Again, the contradiction is a result of the override you propose.Remember that inheritance is a is-a kind of relationship. If
Workeris aPerson, then it should act like aPersonin all ways one expects aPersonto act. If that’s not the kind of relationship you want to create, then do not use inheritance.