Kotlin 's Null safety

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.

    原文作者:一个会写诗的程序员
    原文地址: https://www.jianshu.com/p/a2a448a380cf
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞