do you ever use `when` for just two cases for clar...
# codingconventions
h
do you ever use
when
for just two cases for clarity? e.g.
Copy code
enum class Foo {
    FOO, BAR
}

fun foo(foo: Foo): Int = when(foo) {
    FOO -> "foo"
    BAR -> "bar"
}
or is this basically a no-no, because an single
if
else
can handle it? e.g.
Copy code
fun foo(foo: Foo) = if (foo == FOO) "foo" else "bar"
p
I would definitely use
when
here.
h
I tend to find
when
clearer even in non-enum cases:
Copy code
fun foo(foo: Int) = when(foo) {
    2 -> "two"
    else -> "not two"
}
Maybe I just like the syntax more, or the way everything lines up. The blocking of it, etc
p
I agree, if it is an expression and whole
if
would not fit into one line, then I would use
when
in some cases too 🙂
n
I also use when usually. It improves readibility.
h
it's also great considering in math/boolean logical notation,
A -> B
represents
if A then B
and so it matches that.