angryziber/kotlin-puzzlers

Generic puzzler

Closed this issue · 1 comments

rpuxa commented
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

Man, you are a puzzler genius :-)