I often wanted to be able to decorate java-classes properly, that is add behaviour to them. I know mixins from ruby, and i know that they can get terribly confusing.
I came up with the theoretical idea of having a language-construct like this:
package org.test.decorator;
public decorator ListPatch<E> extends List<E> {
public E last() {
return this.get(this.size() - 1);
}
}
this would give access to public members of List and the Decorator itself.
Then in a class i could use:
package org.test.decorator;
decoration org.test.decorator.ListPatch;
public MyClass {
public void foo() {
List<String> list = Lists.newArrayList();
list.add("test");
System.out.println(list.last());
}
}
I don’t have that much knowledge about compilers, so I wondered if something like that was possible. Also if it actually would be an improvement.
Sure, it’s possible.
The fact that Scala compiles to bytecode (and has a fairly straight forward mapping from Scala classes to bytecode classes) and supports mixins proves this.
Here’s how your sample code looks in Scala syntax:
Scala compiles this by adding an axillary class
Main$$anon$1which composesListTestandListPatch.The motto for the Java developers have always been (and will probably always be) “If in doubt, leave it out.” though.
Related questions: