https://kotlinlang.org logo
Title
h

Hullaballoonatic

06/09/2019, 6:13 PM
do you ever use
when
for just two cases for clarity? e.g.
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.
fun foo(foo: Foo) = if (foo == FOO) "foo" else "bar"
p

Pavlo Liapota

06/09/2019, 6:27 PM
I would definitely use
when
here.
h

Hullaballoonatic

06/09/2019, 6:29 PM
I tend to find
when
clearer even in non-enum cases:
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

Pavlo Liapota

06/09/2019, 6:47 PM
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

necati

06/09/2019, 7:21 PM
I also use when usually. It improves readibility.
h

Hullaballoonatic

06/09/2019, 8:55 PM
it's also great considering in math/boolean logical notation,
A -> B
represents
if A then B
and so it matches that.