when I use the word "var" the IDE gives me an error:
Error:Cannot resolve symbol 'var'
',' or ')' expected
Cannot resolve symbol 'name'
The code:
import static java.lang.System.*;
public class hello {
sealed interface ToGreet {};
record User(String name) implements ToGreet {};
record World() implements ToGreet {};
public static void main(String... args) {
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!");
}
}
}
So why does it happen? How can I solve it?
The pics:



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()isObject. As a result, you should be getting an error saying thatAn enhanced switch statement should be exhaustive; a default label expected.The compiler doesn't infer that this expression always produces a
ToGreetinstance, 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
ToGreetvariable to assign the conditional expression to:Add a default label:
Add a case for
Object: