spnda
05/12/2021, 2:47 PM'if' must have both main and 'else' branches if used as an expression
fun exampleFunc(someBoolean: Boolean) = when (someBoolean) {
else -> {
val otherBoolean = Random.nextBoolean()
if (otherBoolean) {
print("Yay!")
}
}
}
It seems to think it is a ternary, I guess.kqr
05/12/2021, 2:48 PMAdam Powell
05/12/2021, 2:49 PMspnda
05/12/2021, 2:50 PMif (otherBoolean) {
val t = 1
}
yet this wouldn't be a implicit return, yet it still throws the same error
@Adam Powell, I guess...Adam Powell
05/12/2021, 2:52 PMRob Elliot
05/12/2021, 3:15 PMif (otherBoolean) {
val t = 1
}
is a statement, it doesn’t need an else
val t = if (otherBoolean} {
1
}
is an expression, so it needs an else
branch to know what to evaluate t
to if otherBoolean
is false
.
In your when
, the when
needs to be an expression to return a value from the function, so the `when`’s else
block needs to be an expression, so the `if`/`else` needs to be an expression.Stephan Schroeder
05/14/2021, 9:10 AM= when(...) {
Kotlin assumes that a returnvalue is supposed to be given back. But using a multistatement-method form works
fun exampleFunc(someBoolean: Boolean) {
when (someBoolean) {
else -> {
val otherBoolean = Random.nextBoolean()
if (otherBoolean) {
print("Yay!")
}
}
}
}
Rob Elliot
05/14/2021, 9:12 AM