I noticed that this compiles: ```fun foo(): Int { ...
# compiler
r
I noticed that this compiles:
Copy code
fun foo(): Int {
    while (true) {
        return 0
    }
}
But this doesn't (it gives "Return type mismatch: expected 'Int', actual 'Unit"):
Copy code
fun foo(): Int = run {
    while (true) {
        return@run 0
    }
}
This compiles, but warns that the second
0
is unreachable code.
Copy code
fun foo(): Int = run {
    while (true) {
        return@run 0
    }
    0
}
Does anyone know why? And is there any way to write code like the second example without any warnings? (In my case, this is occurring with
coroutineScope
, so I can't just remove it like one could with
run
).
y
Likely a compiler bug. Regardless, you can fix it as such:
Copy code
fun foo(): Int = run {
    forever {
        return@run 0
    }
}

inline fun forever(block: () -> Unit): Nothing {
    while (true) block()
}
r
Thanks! That's a good solution.
y
I knew it sounded familiar! Turns out, I commented on the latter issue with an identical workaround!
😄 2