Last active
October 18, 2023 09:08
-
-
Save adibfara/93db05defef24279e2df467077dfe683 to your computer and use it in GitHub Desktop.
Fixing the double dispatch with default branch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
WeightCalculator.java