Kotlin 's Null safety

作者: 光剑书架上的书 | 来源:发表于2017-09-17 22:30 被阅读34次

    Groovy's approach to null is the same as Java's – it requires you to handle it and guard against it. Its syntactic support for writing null-safe code is enhanced but the underlying problem remains.

    Scala encourages and expects you to use its Option type and kind of pretends null doesn't exist. The problem is that any reference type in Scala (including a reference to Option) can be assigned a null value. Notwithstanding that you shouldn't do that, it can happen. For example when dealing with a Java API or when parsing JSON into a case class. It also means you have to write a wrapper for any legacy Java APIs you use to wrap nullable return types and parameters up in Option instances.

    Kotlin treats a nullable reference to x as a different type to a non-nullable reference to x. This is indicated with a String? on the type name StringString? may be null, BUT String NOT. You must check for null before calling methods or accessing properties on anything potentially null. This is enforced by the compiler.

    The key to understanding what's so great about this is that

    Kotlin's String?

    is an option type like

    Scala's Option[String].

    But it's also backwards compatible with every old Java API that might return null.

    It's syntactically more convenient to deal with than Scala's Option or Java 8's Optional.

    Kotlin's smart casts mean that once you've established that the reference is not null (e.g. in an if or when expression) that reference is automatically cast to the non-nullable type and you can then use it safely.

    相关文章

      网友评论

        本文标题:Kotlin 's Null safety

        本文链接:https://www.haomeiwen.com/subject/iiomsxtx.html