I wanted to model a few interfaces and classes from a typescript codebase. I wanted to know the best way to model the typescript union in Java. Something like this-
export type a = b | c | d | e | f;
export type b = {
..
}
export type c = {
..
}
..
What would be the best way to model this in Java?
Eg:
Class A = Class B or Class C or Class D;
What this means is that A can be an object of any of these Classes.
I am looking for a solution for classes.
But another example would be.
export type numberString = string | number
Actually you can use “Union type” since Java 17 (Java 15+, to be more precise). The introduced sealed and permits keyword can be used to declare “Union types”:
sealed interface Animal permits Dog, Cat {
}
final class Dog extends Animal {
public void bark() {
System.out.println("Woof!");
}
}
final class Cat extends Animal {
public void meow() {
System.out.println("Meow!");
}
}
Java can recognize such “Union types”. For example, in Java 21, when you write something like this:
public class Test {
public static void main(String[] args) {
Animal animal = new Dog();
switch (animal) {
case Dog dog -> {
dog.bark();
}
case Cat cat -> {
cat.meow();
}
}
}
}
Java does not require you to add a redundant default to make the switch expression “exhaustive”. But if you remove the sealed keyword along with permits, you’ll receive an error:
An enhanced switch statement should be exhaustive; a default label expected. Java(2099060)
Also, when you change interface Animal to class Animal, you’ll receive the same error, as the switch expression does not take Animal itself into account, you have to add another match:
Animal animal = new Dog();
switch (animal) {
case Dog dog -> {
dog.bark();
}
case Cat cat -> {
cat.meow();
}
case Animal animal1 -> {
System.out.println("Unknown animal!");
}
}
And that's OK. Java does not report the error anymore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With