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.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,141评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,425评论 0 23
  • 久远的金鸣伴夜色深沉, 归去的相念只在长安城, 做孤鬼徘徊。 那长城下的哭泣为何, 写在历史书中? 时时在庙堂的夜...
    益生阁主阅读 1,274评论 0 0
  • 你问我对这件展品的看法,你只是旁敲侧击的说着,我也言不由衷的搭着。 这件展品是件什么形状呢,你只是言不由衷的描着,...
    飞翔的叟阅读 1,930评论 0 0
  • 本文由币车HIT(biche.yaofache.com)大V养成计划支持 我之前炒股一直在用同花顺,感觉挺实用的。...
    小明外面的世界阅读 1,755评论 1 0