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

  • Functional Kotlin
  • Mario Arias Rivu Chakraborty
  • 349字
  • 2021-06-24 19:15:23

Nullable types

One of the main features of Kotlin is nullable types. Nullable types allow us to define if a value can contain or being null explicitly:

fun main(args: Array<String>) {
val myBlueberryCupcake: Cupcake = null //Compilation error: Null can not be a value of a non-null type Cupcake
}

This isn't valid in Kotlin; the Cupcake type doesn't allow null values. To allow null values, myBlueberryCupcake must have a different type:

fun main(args: Array<String>) {
val myBlueberryCupcake: Cupcake? = null
}

In essence, Cupcake is a non-null type and Cupcake? is a nullable type.

In the hierarchical structure, Cupcake is a subtype of Cupcake?. So, in any situation where Cupcake? is defined, Cupcake can be used, but not the other way around:

fun eat(cupcake: Cupcake?){
// something happens here
}

fun main(args: Array<String>) {
val myAlmondCupcake = Cupcake.almond()

eat(myAlmondCupcake)

eat(null)
}

Kotlin's compiler makes a distinction between instances of nullable and non-null types.

Let's take these values, for example:

fun main(args: Array<String>) {
val cupcake: Cupcake = Cupcake.almond()
val nullabeCupcake: Cupcake? = Cupcake.almond()
}

Next, we will invoke the eat() method on both nullable and non-null types:

fun main(args: Array<String>) {
val cupcake: Cupcake = Cupcake.almond()
val nullableCupcake: Cupcake? = Cupcake.almond()

cupcake.eat() // Happy days
nullableCupcake.eat() //Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Cupcake?
}

Calling the eat() method on cupcake is easy as pie; calling eat() on nullableCupcake is a compilation error.

Why? For Kotlin, calling a method from a nullable value is dangerous, a potential NullPointerException (NPE from now on) could be thrown. So, to be safe, Kotlin marks this as a compilation error.

What happens if we really want to invoke a method or access a property from a nullable value?

Well, Kotlin provides you options to deal with nullable values, with a catch—all are explicit. In some sense, Kotlin is telling you, Show me that you know what you are doing.

Let's review some options (there are more options that we'll cover in the following chapters).

主站蜘蛛池模板: 时尚| 秦皇岛市| 丹东市| 荆门市| 桑日县| 玉环县| 河北区| 南木林县| 六枝特区| 诏安县| 鄂伦春自治旗| 通化市| 治多县| 湘乡市| 滦南县| 池州市| 天柱县| 塔河县| 苍山县| 荣昌县| 宜宾县| 远安县| 莫力| 泰来县| 大英县| 玛纳斯县| 遂昌县| 将乐县| 竹山县| 郁南县| 靖西县| 五华县| 江门市| 修水县| 双峰县| 上饶市| 厦门市| 红河县| 隆子县| 宁陵县| 县级市|