Kotlin 学习之Null Safety

  Kotlin对比于Java的一个最大的区别就是它致力于消除空引用所带来的危险。在Java中,如果我们尝试访问一个空引用的成员可能就会导致空指针异常NullPointerException(NPE)的出现。

The Billion Dollar Mistake

  在2009年的一个会议中,著名的“快速排序”算法的发明者,Tony Hoare向全世界道歉,忏悔他曾经发明了“空指针”这个玩意。

  I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language(ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.

在Kotlin语言中就解决了这个问题,下面来看看它是如何做到的。

  • Nullable types and Non-Null Types

  类型系统将可空类型和不可空类型进行了区分,例如,String为不可空类型,String?为可空类型,如果将不可空类型赋值为null将会编译不通过。

    var a: String = "abc"
    val m = a.length
    a = null // compilation error

    var b: String? = "abc"
    val n = b.length // error: variable 'b' can be null
    b = null // ok
  • Safe Calls
      对于不可空类型,可以直接调用它的成员变量或者函数,但是对应可空类型,直接调用成员变量或者函数将会编译不通过,可空引用有一种安全的调用方式,使用?.进行调用。
    var b: String? = "abc"
    b = null // ok
    val l = b?.length
    println(l)

如果b为null,则b?.length返回null,否则返回b.length,如果我们不希望返回null,可以用?:赋值

    var b: String? = "abc"
    b = null // ok
    val l = b?.length?:-1
    println(l)

如果b为null,则返回-1,,b不为null,返回b.length,类似java中的三目运算符

  • The !! Operator
    var b: String? = "abc"
    b = null // ok
    val l = b!!.length

如果b为null,则直接抛出异常kotlin.KotlinNullPointerException

  • Safe Casts
    val a: String = "12"
    val aInt: Int? = a as? Int
    println(aInt)

如果类型不一致,直接返回null而不是抛出异常ClassCastException,暂时不太明白强转的意义在哪。而且返回null也是不安全的。

  • Collections of Nullable Type
    val nullableList: List = listOf(1, 2, null, 4)
    val intList: List = nullableList.filterNotNull()
    println(intList)

输出[1, 2, 4],过滤集合中的null值

参考资料
The Billion Dollar Mistake
http://kotlinlang.org
Kotlin学习笔记——Kotlin中的null安全

你可能感兴趣的:(Kotlin 学习之Null Safety)