https://kotlinlang.org logo
#getting-started
Title
# getting-started
n

Norbi

02/04/2023, 12:30 PM
I'm experimenting with context receivers (with Kotlin 1.8.0) and I have run into strange things. One problem is that this code runs normally and prints
4
to the console:
Copy code
@Test
fun testBug() {
    runBlocking {
        println(f(2) { this() })
    }
}

suspend fun <T> f(value: Int, block: context(A) Int.() -> T): T = block(A(), value)

class A {
    operator fun Int.invoke() = this * 2
}
But making all functions suspend results in a runtime exception:
Copy code
@Test
fun testBug() {
    runBlocking {
        println(f(2) { this() })
    }
}

suspend fun <T> f(value: Int, block: suspend context(A) Int.() -> T): T = block(A(), value)

class A {
    suspend operator fun Int.invoke() = this * 2
}
Copy code
java.lang.ClassCastException: class A cannot be cast to class java.lang.Number
Is this a bug? (Please ignore what the code actually does, it is just an excerpt to reproduce the issue.)
3 Views