Java 17 : switch expressions and statements
Asked Answered
L

1

5

I don't understand why the first snippet compiles fine :

var res = getResult(s);

public static double getResult(Shape s)  {
        switch(s) {
            case Rectangle r : return 2* r.largeur() + 2* r.longueur();
            case Circle c : return  2*c.radius();
            default : throw new RuntimeException("not a shape");
        }
}

But not this one :

var res = switch(s) {
            case Rectangle r : return 2* r.largeur() + 2* r.longueur();
            case Circle c : return  2*c.radius();
            default : throw new RuntimeException("not a shape");
        };

It looks the same for me.

Longobard answered 23/5, 2023 at 10:30 Comment(1)
What does the compiler say?Dateline
M
10

Your first variant is a statement. The second is using switch as an expression, hence, you can’t return from the cases but have to yield a value (unless throwing an exception).

var res = switch(s) {
    case Rectangle r: yield 2 * r.largeur() + 2 * r.longueur();
    case Circle c: yield 2 * c.radius();
    default: throw new RuntimeException("not a shape");
};

but it makes more sense to use the new syntax:

var res = switch(s) {
    case Rectangle r -> 2 * r.largeur() + 2 * r.longueur();
    case Circle c -> 2 * c.radius();
    default -> throw new RuntimeException("not a shape");
};
Mam answered 23/5, 2023 at 12:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.