I want to have an enum that provides a function that includes a constructor of a new class. Before Java8 I used to write this code:
enum Fruit1 {
APPLE, BANANA;
public Tree getTree() {
switch (this) {
case APPLE:
return new AppleTree();
case BANANA:
return new BananaTree();
default:
throw new IllegalStateException();
}
}
}
Now, I can use lambda expressions. The advantage is, when adding a new enum entry, you cannot forget adding sth to the switch statement. But I dont like that the code looks more complicated to me.
enum Fruit2 {
APPLE(AppleTree::new), BANANA(BananaTree::new);
Supplier<Tree> treeSupplier;
Fruit2(Supplier<Tree> treeSupplier) {
this.treeSupplier = treeSupplier;
}
public Tree getTree() {
return treeSupplier.get();
}
}
Is it just a matter of taste or is there more to it? Can I do it in a nicer way using lambda expressions?
This is strongly related to other questions comparing lambda expressions to abstract methods, but here I would like to focus on the switch expression, that I am still quite comfortable with (in comparison to lambda expressions).