- Functional Kotlin
- Mario Arias Rivu Chakraborty
- 139字
- 2021-06-24 19:15:24
The Nothing type
Nothing is the type that sits at the bottom of the entire Kotlin hierarchy. Nothing extends all Kotlin types, including Nothing?.
But, why do we need a Nothing and Nothing? types?
Nothing represents an expression that can't be executed (basically throwing exceptions):
val result: String = nullableCupcake?.eat() ?: throw RuntimeException() // equivalent to nullableCupcake!!.eat()
On one hand of the Elvis operator, we have a String. On the other hand, we have Nothing. Because the common type between String and Nothing is String (instead of Any), the value result is a String.
Nothing also has a special meaning for the compiler. Once a Nothing type is returned on an expression, the lines after that are marked as unreachable.
Nothing? is the type of a null value:
val x: Nothing? = null
val nullsList: List<Nothing?> = listOf(null)
推薦閱讀
- 演進式架構(原書第2版)
- OpenStack Cloud Computing Cookbook(Third Edition)
- Visual Basic .NET程序設計(第3版)
- 國際大學生程序設計競賽中山大學內部選拔真題解(二)
- SpringMVC+MyBatis快速開發與項目實戰
- HTML5 and CSS3 Transition,Transformation,and Animation
- Mastering JavaScript High Performance
- Getting Started with React Native
- Learning AWS
- Laravel Application Development Blueprints
- 一步一步跟我學Scratch3.0案例
- OpenCV Android Programming By Example
- ASP.NET開發寶典
- 3D Printing Designs:Octopus Pencil Holder
- HTML5與CSS3權威指南