Weird Coroutines and If-else Behaviour

fun main() = runBlocking {
    var TEST = 8
    var CHECK = 2
    if(CHECK == TEST) {
        println("CHECK == TEST")
    } else if(CHECK < TEST) {
        CoroutineScope(Dispatchers.IO).launch {
            println("CHECK < TEST")
    } else if(CHECK > TEST) {
        println("CHECK > TEST")

The above code is giving ERROR its a very simple IF-ELSE block the 1st ELSE-IF block is giving error because it has Coroutine. If I remove the Coroutine from that block then everything is fine. Can anyone please explain me the reason why this is happening.
Attached Images of IDE below :

But If I put any statement after the Coroutine The the error is gone

Please Help!

Problem is return value.
When you launch coroutine it will return Job, and if-structure will deduce that you want to return something as a result of expression.
When you added println, return type changed to Unit, so you don’t really need else branch.

1 Like

This may be confusing indeed and it is a consequence of several Kotlin features that sometimes result with weird behavior.

  1. You didn’t specify what is the return type of main(), so it is inferred from the return type of runBlocking().
  2. You didn’t specify what is the return type of runBlocking() as well, so it is inferred from the lambda inside.
  3. Lambdas by default return the value of the last expression - if in your example.
  4. Kotlin tries to return the value of if, but if doesn’t return anything in the second case. This causes error.

To fix this, you need to specify manually that you don’t intend to return anything. Use main(): Unit or runBlocking<Unit>.

It would be easier if you don’t remove your post earlier. I wrote my answer yesterday, but before I was able to send it, the post was removed. Now I see it appeared again.