суббота, 15 марта 2014 г.

Multiple dispatch in Java

Today I found a good FP library which is called totallylazy. This library has a lot of great features like persistent collections, options and streams (they call it Computation), but it also has a very good feature, which makes it possible to write multimethods in Java. I think, multiple dispatch is a great tool that makes code much more concise and cleaner. This is how it looks:

       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.