angryziber / kotlin-puzzlers

A collection of Kotlin Puzzlers
419 stars 58 forks source link

Kotlin is type safety and null safety language (no) #55

Closed rpuxa closed 4 years ago

rpuxa commented 5 years ago
fun main() {
    val write = { a: Byte -> print("$a ") }

    val typeSafety =
            if (write as? (Double) -> Unit == null) {
                true
            } else {
                write(127)
                write(128.9)
                false
            }

    val nullSafety =
            if (write as? (Any?) -> Unit == null) {
                true
            } else {
                try {
                    write(null)
                    true
                } catch (e: java.lang.NullPointerException) {
                    false
                }
            }

    when {
        typeSafety && nullSafety -> println("Kotlin is type safety and null safety language")
        typeSafety -> println("Kotlin is type safety language")
        nullSafety -> println("Kotlin is null safety language")
        else -> println("Kotlin is a language")
    }
}

If you use "as?" for checking lambdas, Kotlin will check only arity but not arguments types

angryziber commented 4 years ago

It seems this is no longer true for Kotlin 1.3.50, now it fails with compile errors. The compiler is improving :-)

rpuxa commented 4 years ago

(╯°□°)╯︵ ┻━┻