This page is no longer maintained — Please continue to the home page at www.scala-lang.org

preventing addition of Base and Derived classes

1 reply
Russ P.
Joined: 2009-01-31,
User offline. Last seen 1 year 26 weeks ago.

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.

Naftoli Gugenheim
Joined: 2008-12-17,
User offline. Last seen 42 years 45 weeks ago.
preventing addition of Base and Derived classes
What should happen if you do:
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:
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.

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland