I don't know why you are getting this particular error message. The actual reason the code doesn't compile is different.
The type of the conditional expression args.length > 0 ? new User(args[0]) : new World()
is Object
. As a result, you should be getting an error saying that An enhanced switch statement should be exhaustive; a default label expected
.
The compiler doesn't infer that this expression always produces a ToGreet
instance, so it's not sufficient to specify cases for the two possible implementations of this sealed interface.
The are several options to fix the error.
Use an intermediate ToGreet
variable to assign the conditional expression to:
ToGreet greet = args.length > 0 ? new User(args[0]) : new World();
switch (greet) {
case User(var name) -> out.println("Hello " + name);
case World w -> out.println("Hello World!");
}
Add a default label:
switch (args.length > 0 ? new User(args[0]) : new World()) {
case User(var name) -> out.println("Hello " + name);
case World w -> out.println("Hello World!");
default -> throw new IllegalArgumentException ();
}
Add a case for Object
:
switch (args.length > 0 ? new User(args[0]) : new World()) {
case User(var name) -> out.println("Hello " + name);
case World w -> out.println("Hello World!");
case Object o -> throw new IllegalArgumentException ();
}