AlexD
11/13/2024, 6:57 PMif (isValidInput) {
doSomething()
doSomethingElse()
} else {
handleInputError()
}
2️⃣
when {
isValidInput -> {
doSomething()
doSomethingElse()
}
else -> handleInputError()
}
Youssef Shoaib [MOD]
11/13/2024, 7:00 PMrequire(isValidInput)
Pablichjenkov
11/13/2024, 7:14 PM2
AlexD
11/13/2024, 7:23 PMPablichjenkov
11/13/2024, 7:51 PM2
is clearer in my preference.Rob Elliot
11/13/2024, 8:27 PMwhen
nicer to read than an if
.horse_badorties
11/14/2024, 6:41 AMif (..) {
..
} else handleInputError()
any different from
when {
.. -> {
..
}
else -> handleInputError()
}
in that regard?
Do you guys mind single line if..else without braces?horse_badorties
11/14/2024, 7:06 AMif..else
?andries.fc
11/14/2024, 8:20 AM// Just logic
if (x == 3)
doSomething()
else
doSomethingElse()
// Assignment
val r = when {
x == 3 -> calculateSomething(x)
else -> calculateSomethingElse(x)
}
David Kubecka
11/14/2024, 8:47 AMRobert Williams
11/14/2024, 10:42 AMif
version is if someone adds a new statement
if (..) {
..
} else handleInputError()
newStatementThatShouldBeInElse()
it'll still be valid code, it just won't do what's expected
But in the when version
when {
.. -> {
..
}
else -> handleInputError()
newStatementThatShouldBeInElse()
}
This will be a compile error without the bracesKlitos Kyriacou
11/14/2024, 11:43 AMif
-without-braces to be a real issue, despite hearing warnings about it many times. It's easy to see that an else
part has no braces and to add them when adding a second statement. One thing I do, however, for the sake of consistency, is that if the if
part uses braces, then I ensure the else
part uses braces too, and vice versa.andries.fc
11/14/2024, 12:24 PMKai Yuan
11/16/2024, 12:15 AMPrefer usinghttps://kotlinlang.org/docs/coding-conventions.html#if-versus-whenif there are three or more options.when
andries.fc
11/16/2024, 1:32 PMwhen
statement, and no if
statement at all. There is something to be said for language with less syntax than more. In the same vain I find it exceedingly pleasant not to use a semicolon at all.