Are there a recommended practice about when to use...
# announcements
p
Are there a recommended practice about when to use an if and when to use a when expression?
e
Not specifically, as far as I know. Use common sense and good judgement. Personally, I’d say, strongly prefer when if one of these is true: • it is similar to a “classic switch”, i.e. the decision logic depends on the value of a single expression • the construct is used to set a variable/return value, so that you can use the when as an expression where every branch returns something • you have more than two branches and each branch does something conceptually similar. That avoids long if-elseif-elseif-else constructs.
s
Agree with the above. However, it can also be perfectly readable/understandable to use `if`/`else` as expressions as well (point 2), that's not reserved for
when
expressions.
k
Once I have an
if .. else if .. else
I usually just switch it to a
when
, I think it's more readable to have all conditions right above each other on the same indent.
1
m
And IntelliJ makes it very easy to switch back and forth if you're unsure about which you like better.
👍 1
p
I have a co-worker who never uses
if
but always
when
. It would be great to have an official reference on this because I don't have any arguments besides my personal taste ;-)
s
In this case, I feel like it makes sense for each team to set themselves some guidelines/“rules”.