angryziber / kotlin-puzzlers

A collection of Kotlin Puzzlers
419 stars 58 forks source link

Returning wrong type object from suspend function #61

Closed rpuxa closed 4 years ago

rpuxa commented 4 years ago
fun printAndReturn(string: String): Int {
    print(string)
    return 43
}

suspend fun suspendFunction(): String =
    suspendCoroutineUninterceptedOrReturn {
        printAndReturn("42 ")
    }

suspend fun main() {
    print(suspendFunction())
}

1) 42 43 2) 42 ClassCastException 3) Will not compile 4) None of the above

Correct answer: 1. As far as i understand all suspend functions have an Object as return type (thats why there is no ClassCastException) and suspendCoroutineUninterceptedOrReturn allows you to return anything regardless return type (its needed for some library functions)

rpuxa commented 4 years ago

By the way you can "allocate" Nothing class using this method suspend fun suspendFunction(): Nothing = suspendCoroutineUninterceptedOrReturn {}

angryziber commented 4 years ago

Thanks for awesome coroutine puzzlers! How did you come up with calling of suspendCoroutineUninterceptedOrReturn() directly?

rpuxa commented 4 years ago

If you look at iterator() source code, you can see how yield() function use suspendCoroutineUninterceptedOrReturn() for returning COROUTINE_SUSPENDED (its special value for coroutine suspension and im trying to create new puzzler with it at the moment), but having Unit as return type. After that I've condacted some experiments and that's why you can see this puzzler