angryziber / kotlin-puzzlers

A collection of Kotlin Puzzlers
419 stars 58 forks source link

Generic puzzler #65

Closed rpuxa closed 4 years ago

rpuxa commented 4 years ago
fun <T> weirdPrint(a: ArrayList<in T>) =
    try {
        print(a) as T
    } catch (e: Throwable) {
        throw UnsupportedOperationException()
    }

weirdPrint(if (false) arrayListOf(42) else arrayListOf("Hello"))

// a) [Hello] // b) [Hello] NullPointerException // c) [Hello] UnsupportedOperationException // d) Will not compile

Correct answer is b. T implicitly infers to Nothing and if function returns Nothing, compiler inserts "throw null" after invocation. Why "throw null"? Because its shortest way to throw any exception

angryziber commented 4 years ago

Man, you are a puzzler genius :-)