- 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 Cython Programming
- Spring技術內幕:深入解析Spring架構與設計
- Arduino開發實戰指南:LabVIEW卷
- Hands-On Natural Language Processing with Python
- Advanced Oracle PL/SQL Developer's Guide(Second Edition)
- Julia高性能科學計算(第2版)
- Unity UI Cookbook
- Android項目實戰:手機安全衛士開發案例解析
- ServiceNow:Building Powerful Workflows
- Node.js 12實戰
- Arduino Wearable Projects
- Web程序設計:ASP.NET(第2版)
- Go語言從入門到精通
- Visual Basic程序設計基礎
- Test-Driven iOS Development with Swift