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

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
主站蜘蛛池模板: 中江县| 家居| 陆河县| 兴国县| 镇沅| 西丰县| 佳木斯市| 镇江市| 依安县| 澎湖县| 清河县| 酉阳| 伊川县| 砀山县| 禄劝| 通城县| 江都市| 甘肃省| 望江县| 安丘市| 马边| 扬州市| 白玉县| 黔西县| 南昌县| 略阳县| 棋牌| 昌邑市| 全州县| 买车| 永济市| 永年县| 石家庄市| 阿鲁科尔沁旗| 敦化市| 饶平县| 北票市| 鱼台县| 靖江市| 宣城市| 哈密市|