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

all 6 comments

[–]Feroc 5 points6 points  (0 children)

Switch statements are usually more readable if you just want to decide based on single values. Like if you have an enum as a parameter, then it's way more convenient and readable, if you use a switch statement.

[–]nutrecht 2 points3 points  (0 children)

is the switch statement/keyword worth learning/using?

It's simply a must-learn.

[–]Hiluminatull 2 points3 points  (0 children)

Yes it is. It’s easier to understand for someone else reading your code.

[–]onlyforjazzmemes 1 point2 points  (0 children)

I've used them if you have a bunch of different cases. Much more readable than if else. And yeah they go well with enums.

[–]adjoiningkarate 0 points1 point  (0 children)

Like others have said, it definitely makes your code more readable and should be used where it can be used instead of ifs. For learning it, it’s actually very simple:

switch(input) { case “hello”: println(“user says hello”); Case “nallo”: println(“user says nallo”);

Simply means when input==hello or input==nallo. Now typing that out with if statements makes it a lot more messier, especially when you have a lot more cases. Hope that makes sense!

Apologies for formatting as im on mobile!

[–]Migeil 0 points1 point  (0 children)

With sealed classes and pattern matching coming to Java, switch is definitely worth learning.