Are there a recommended practice about when to use an if and when to use a when expression?
e
eekboom
10/22/2019, 7:56 AM
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
sindrenm
10/22/2019, 8:21 AM
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
karelpeeters
10/22/2019, 8:29 AM
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
Mike
10/22/2019, 2:58 PM
And IntelliJ makes it very easy to switch back and forth if you're unsure about which you like better.
👍 1
p
Paul Woitaschek
10/23/2019, 6:31 AM
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
sindrenm
10/23/2019, 6:36 AM
In this case, I feel like it makes sense for each team to set themselves some guidelines/“rules”.