JetBrains / kotlin-playground

Self-contained component to embed in websites for running Kotlin code
https://jetbrains.github.io/kotlin-playground/examples/
Apache License 2.0
447 stars 80 forks source link

Unexpected println output #196

Closed vadimsemenov closed 7 months ago

vadimsemenov commented 10 months ago

https://pl.kotl.in/wxbNjiZXx

import kotlinx.coroutines.*
import kotlin.coroutines.*

fun main() {
    val foo = Foo()
    foo.foo(1, CoroutineScope(EmptyCoroutineContext))
    foo.foo(2, CoroutineScope(EmptyCoroutineContext).also { it.cancel() })
}

class Foo {
    fun foo(id: Int, scope: CoroutineScope) {
        println("Starting $id")
        val job = scope.launch {
            delay(1000)
        }
        job.invokeOnCompletion {
            println("onCompletion $id")
        }
        println("Finishing $id")
    }
}

Outputs

onCompletion 2 Starting 1
Finishing 1
Starting 2
Finishing 2

I'd expect it to print

Starting 1
Finishing 1
Starting 2
Finishing 2

(and maybe "onCompletion 2" after "Starting 2")

zoobestik commented 7 months ago

There is issue for backend: https://github.com/JetBrains/kotlin-compiler-server/pull/618

phiSgr commented 7 months ago

There is issue for backend

To be precise, there is a fix for the backend waiting to be merged.