官术网_书友最值得收藏!

  • 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)
主站蜘蛛池模板: 禹州市| 开封县| 宜兰县| 宿迁市| 新乐市| 贺兰县| 镇雄县| 柳州市| 无棣县| 临海市| 大宁县| 蓝田县| 丰原市| 海丰县| 营山县| 巫溪县| 连江县| 焉耆| 龙口市| 东安县| 监利县| 介休市| 维西| 崇义县| 仲巴县| 厦门市| 宣威市| 宁河县| 祁阳县| 嘉荫县| 喜德县| 抚宁县| 东台市| 梓潼县| 青冈县| 台南县| 辽中县| 星子县| 榕江县| 灵川县| 祁阳县|