- 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
- Mastering ServiceStack
- 大學計算機應用基礎實踐教程
- Three.js開發指南:基于WebGL和HTML5在網頁上渲染3D圖形和動畫(原書第3版)
- Mastering Kotlin
- 基于Java技術的Web應用開發
- AppInventor實踐教程:Android智能應用開發前傳
- 區塊鏈技術與應用
- Create React App 2 Quick Start Guide
- 動手學數據結構與算法
- Java語言程序設計教程
- 深入實踐DDD:以DSL驅動復雜軟件開發
- SignalR:Real-time Application Development(Second Edition)
- Anaconda數據科學實戰
- C語言程序設計