Is it possible in Scala to write something like:
trait Road {
...
}
class BridgeCauseway extends Road {
// implements method in Road
}
class Bridge extends Road {
val roadway = new BridgeCauseway()
// delegate all Bridge methods to the `roadway` member
}
or do I need to implement each of Road
's methods, one by one, and call the corresponding method on roadway
?
The easiest way to accomplish this is with an implicit conversion instead of a class extension:
as long as you don't need the original
Bridge
to be carried along for the ride (e.g. you're going to storeBridge
in a collection ofRoad
).If you do need to get the
Bridge
back again, you can add anowner
method inRoad
which returns anAny
, set it using a constructor parameter forBridgeCauseway
, and then pattern-match to get your bridge:If you can make
Bridge
atrait
you'll be sorted.