Created
October 18, 2023 09:28
-
-
Save adibfara/16fec037d37f6333762c9526099365c9 to your computer and use it in GitHub Desktop.
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 sealed interface Item permits Box, Container { } |
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); | |
// the default case is removed | |
}; | |
} | |
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