I’m looking for a neat way to implement a cool design pattern for my geometry collection. Right now I’ve got a trait called Geometry at the top of my geometry type hierarchy. The idea is to let every geometry inherit the trait and then implement specific code for the specific types of geometry. As geometric objects these geometries needs to implement various methods of course. Take for example the ability to calculate the distance to any other geometry – I’ve termed that distanceTo. The most clean way to do it must be to have a method in the Geometry trait like so:
def distanceTo(geometry : Geometry) : Double
My problem is this: How do I implement this method in a geometry (say a Rectangle) without having to type-check for every shape that exists? Are there any handy ways to delegate the requests to the individual geometries?
Cheers,
Since Scala doesn’t have multiple dispatch, your best bet is pattern matching on pairs of geometric objects. Something like
You could then define a convenience method on the
Geometrytrait that calls this method. IfGeometryis a sealed trait, the compiler will even warn you about missing cases when pattern matching.