public String
collide(Object obj1, Object obj2) {
return new
multi(){}.<String> methodOption(obj1, obj2).getOrThrow(
new
IllegalArgumentException("No method
found for args: " +
obj1.getClass() + ", " + obj2.getClass()));
}
@multimethod
public String collide(Asteroid asteroid,
Spaceship spaceship) {
return "Asteroid hits spaceship";
}
@multimethod
public String collide(Asteroid asteroid,
Asteroid asteroid2) {
return "Asteroid hits another asteroid";
}
@multimethod
public String collide(Spaceship spaceship,
Asteroid asteroid) {
return "Spaceship hits asteroid";
}
@multimethod
public String collide(Spaceship spaceship,
Spaceship spaceship2) {
return "Spaceship hits another spaceship";
}
This is a classis example of multiple dispatch taken from Wiki. So if you pass two objects to the collide method, the method with most specific parameter types will be picked:
Object a = new Asteroid();
Object s = new Spaceship();
System.out.println(collide(a,
s)); // Prints "Asteroid hits spaceship"
Of course, this uses internally some sort of reflection and this is not as fast as static method linking. But since the famous rule says "Avoid premature optimization", you should not be afraid to write such code.