- 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
- Learning Spring 5.0
- Debian 7:System Administration Best Practices
- 網(wǎng)店設(shè)計看這本就夠了
- PLC應(yīng)用技術(shù)(三菱FX2N系列)
- “笨辦法”學(xué)C語言
- GameMaker Essentials
- CodeIgniter Web Application Blueprints
- 寫給大家看的Midjourney設(shè)計書
- Docker:容器與容器云(第2版)
- Android高級開發(fā)實戰(zhàn):UI、NDK與安全
- 從“1”開始3D編程
- VMware vSphere 5.5 Cookbook
- iOS Development with Xamarin Cookbook
- Less Web Development Cookbook
- Dart:Scalable Application Development