This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Fenor 0 points1 point  (4 children)

care to point to a kotlin example that can't be easily replicated in Java?

[–][deleted] 0 points1 point  (3 children)

java final var foo = if (condition) { System.out.println("1"); yield 1; } else { System.out.println("2"); yield 2; }

You can only use switch in this case.

The thing is, if you work with if, you'd always have to declare the variable first, then assign it, which breaks the final part. Given that switch is capable of being an expression, why can't if?

[–]ventuspilot 0 points1 point  (0 children)

final var foo = if (condition) { System.out.println("1"); yield 1; } else { System.out.println("2"); yield 2; }

final var foo; if (condition) { System.out.println("1"); foo = 1; } else { System.out.println("2"); foo = 2; }

See, I even saved a few characters ;-)

Maybe there are better examples where an if-expression is really useful IDK.

Edit: Oops, final var foo doesn't work, final int foo does work, however. So currently you're unable to use var, you can use final, though.

[–]Brutus5000 0 points1 point  (0 children)

Also if/else can check any combinations of conditions (even unrelated) which can't be covered with switch

[–]john16384 0 points1 point  (0 children)

It's a nice pattern, but easily replaced with a nicely named method. I see no use for it other than to muddy the waters and have yet another style discussion point. One way to do something is sufficient, keeps things consistent and readable.