Skip to content

Instantly share code, notes, and snippets.

@adibfara
Last active October 18, 2023 09:08
Show Gist options
  • Save adibfara/93db05defef24279e2df467077dfe683 to your computer and use it in GitHub Desktop.
Save adibfara/93db05defef24279e2df467077dfe683 to your computer and use it in GitHub Desktop.
Fixing the double dispatch with default branch
public class WeightCalculator {
public int calculate(Item item) {
return switch (item) {
case Box box -> calculate(box);
case Container container -> calculate(container);
default -> throw new IllegalStateException("Unexpected value: " + item);
};
}
public int calculate(Box box) {
return box.size();
}
public int calculate(Container container) {
int sum = 2;
for (Item item : container.items()) {
sum += calculate(item);
}
return sum;
}
}
@0AT2536
Copy link

0AT2536 commented Oct 18, 2023

WeightCalculator.java

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment