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

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

Minimum common types

Due to its type inference and expression evaluation, sometimes there are expressions in Kotlin where it is not clear which type is being returned. Most languages resolve this problem by returning the minimum common type between the possible type options. Kotlin takes a different route.

Let's take a look at an example of an ambiguous expression:

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

val length = nullableCupcake?.eat()?.length ?: ""
}

What type does length have? Int or String? No, length value's type is Any. Pretty logical. The minimum common type between Int and String is Any. So far, so good. Let's look at the following code now:

val length = nullableCupcake?.eat()?.length ?: 0.0

Following that logic, in this case, length should have the Number type (the common type between Int and Double), shouldn't it?

Wrong, length is still Any. Kotlin doesn't search for the minimum common type in these situations. If you want a specific type, it must be explicitly declared:

val length: Number = nullableCupcake?.eat()?.length ?: 0.0
主站蜘蛛池模板: 宁武县| 大同县| 清水河县| 永川市| 兴隆县| 台中县| 崇明县| 贡山| 长丰县| 陆河县| 威海市| 河曲县| 龙里县| 永川市| 台安县| 额济纳旗| 霍城县| 万宁市| 电白县| 兰溪市| 洮南市| 元朗区| 马山县| 广灵县| 南召县| 和顺县| 新巴尔虎左旗| 绥化市| 江北区| 西和县| 云霄县| 南阳市| 松原市| 大英县| 孝义市| 包头市| 酒泉市| 青河县| 台中市| 东方市| 大庆市|