- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
preventing addition of Base and Derived classes
Wed, 2012-02-08, 09:04
Suppose I have the following trivial Base and Derived classes:
class Base() {
def + (b: Base) = new Base
}
class Derived() extends Base() {
def + (d: Derived) = new Derived
}
object XTest {
def main(args: Array[String]) {
val b = new Base
val d = new Derived
println()
println("Base + Base = " + (b + b))
println("Base + Derived = " + (b + d))
println("Derived + Base = " + (d + b))
println("Derived + Derived = " + (d + d))
println()
}
}
The output of the XTest is this:
Base + Base = Base@2ade1cb6
Base + Derived = Base@5c2f06b6
Derived + Base = Base@1361c602
Derived + Derived = Derived@780eb73e
Is it possible to modify this code in such a way that the compiler
allows Bases objects to be added to each other and allows Derived
objects to be added to each other but rejects any attempt to add a
Base and a Derived object? In other words:
Base + Base <-- compiles
Derived + Derived <-- compiles
Base + Derived <-- should not compile
Derived + Base <-- should not compile
Thanks.
--Russ P.
val b = new Baseval d: Base = new Derivedb + d
Do you see the problem? That's what the Liskov Substitution Principle is about: a subtype has to conform to its supertype.
On Wednesday, February 8, 2012, Russ P. wrote: