Did I just find a bug with the Kotlin compiler? Th...
# announcements
s
Did I just find a bug with the Kotlin compiler? The following example throws an error at line 4:
'if' must have both main and 'else' branches if used as an expression
Copy code
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.
k
isn't that because last expression is implicit return?
☝️ 4
a
Specifically because you've defined the function as an expression using = when
s
Copy code
if (otherBoolean) {
    val t = 1
}
yet this wouldn't be a implicit return, yet it still throws the same error @Adam Powell, I guess...
a
The contents of the if block don't matter, without an else it's not a valid expression
r
Copy code
if (otherBoolean) {
    val t = 1
}
is a statement, it doesn’t need an
else
Copy code
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.
💯 5
s
with
= when(...) {
Kotlin assumes that a returnvalue is supposed to be given back. But using a multistatement-method form works
Copy code
fun exampleFunc(someBoolean: Boolean) {
  when (someBoolean) {
    else -> {
      val otherBoolean = Random.nextBoolean()
      if (otherBoolean) {
        print("Yay!")
      }
    }
  } 
}
r
edited: Apologies, misread your post