0
点赞
收藏
分享

微信扫一扫

Kotlin 's Null safety

49路末班车 2022-06-09 阅读 134

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 ​​String​​​ — ​​String?​​​ 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.



举报

相关推荐

0 条评论