I’m not sure if this is a bug, but it’s quite odd.
If I do
fun foo(): Int {
while (true) {
if (doSomeWork()) return 42
}
}
this compiles fine, because when (if) this function returns, it returns an int.
However if I try to do this in a lambda body
fun foo(): Int {
return run<Int> {
while (true) {
if (doSomeWork()) return@run 42
} // Type mismatch. Required: Int; Found: Unit
}
}
the compiler complains that the body returns Unit
instead of Int
.
Throwing an exception after this loop fixes the problem, but the compiler will now (rightfully) complain that the exception is never thrown… which implies that it should’ve compiled in the first place.
fun foo(): Int {
return run<Int> {
while (true) {
if (doSomeWork()) return@run 42
}
throw IllegalStateException() // Unreachable code; Throwable instance 'IllegalStateException' is not thrown
}
}
This is highly simplified; I’m actually running into this problem with coroutine builders, but the issue is the same.
(Kotlin 1.3.72)