Skip to content

Instantly share code, notes, and snippets.

@fatso83
Last active October 8, 2025 09:41
Show Gist options
  • Save fatso83/33edb31decdf9c9ce7be109ec9089834 to your computer and use it in GitHub Desktop.
Save fatso83/33edb31decdf9c9ce7be109ec9089834 to your computer and use it in GitHub Desktop.
Sealed classes switching on instanceof
import java.util.List;
/*
* ❯ java ./SealedSwitch.java
* SHIZZLES FOR MY NIZZLES!!!
* Whooof!
* Whooof!
* Whooof!
*/
public class SealedSwitch {
sealed interface Effect permits Shout, Bark {
}
record Shout(String value) implements Effect { }
record Bark(int times) implements Effect {}
public static void main(String ...args){
final var effects = List.of(new Shout("Shizzles for my nizzles"), new Bark(3));
for(var effect: effects) {
switch(effect) {
case Bark b -> {
for(int i = 0; i < b.times; i++)
System.out.println("Whooof!");
}
case Shout s -> System.out.println(s.value.toUpperCase() + "!!!");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment