1

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:

Problems
Settings
Structure

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Anatoly
  • 3,266
  • 4
  • 17
  • 28

1 Answers1

0

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 ();
}
Eran
  • 387,369
  • 54
  • 702
  • 768