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

  • 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
主站蜘蛛池模板: 岳普湖县| 河池市| 乌审旗| 永顺县| 张家口市| 开平市| 东乡族自治县| 沧州市| 长沙市| 达日县| 双城市| 类乌齐县| 磴口县| 五原县| 响水县| 吐鲁番市| 黄山市| 石狮市| 荃湾区| 博客| 安多县| 安阳县| 通州区| 文登市| 普安县| 锡林郭勒盟| 英吉沙县| 梧州市| 顺义区| 大同市| 林甸县| 东兰县| 常德市| 久治县| 广东省| 蓬溪县| 宣威市| 池州市| 长阳| 游戏| 克拉玛依市|