- Functional Kotlin
- Mario Arias Rivu Chakraborty
- 169字
- 2021-06-24 19:15:24
The Any type
All types in Kotlin extend from the Any type (hold on a second, actually this isn't true but for the sake of the explanation, bear with me).
Every class and interface that we create implicitly extends Any. So, if we write a method that takes Any as a parameter, it will receive any value:
fun main(args: Array<String>) {
val myAlmondCupcake = Cupcake.almond()
val anyMachine = object : Machine<Any> {
override fun process(product: Any) {
println(product.toString())
}
}
anyMachine.process(3)
anyMachine.process("")
anyMachine.process(myAlmondCupcake)
}
What about a nullable value? Let's have a look at it:
fun main(args: Array<String>) {
val anyMachine = object : Machine<Any> {
override fun process(product: Any) {
println(product.toString())
}
}
val nullableCupcake: Cupcake? = Cupcake.almond()
anyMachine.process(nullableCupcake) //Error:(32, 24) Kotlin: Type mismatch: inferred type is Cupcake? but Any was expected
}
Any is the same as any other type and also has a nullable counterpart, Any?. Any extends from Any?. So, in the end, Any? is the top class of Kotlin's type system hierarchy.
推薦閱讀
- Functional Python Programming
- The Complete Rust Programming Reference Guide
- 控糖控脂健康餐
- 青少年美育趣味課堂:XMind思維導圖制作
- 營銷數據科學:用R和Python進行預測分析的建模技術
- Learning ELK Stack
- Linux操作系統基礎案例教程
- 小程序開發原理與實戰
- 青少年信息學競賽
- ASP.NET程序開發范例寶典
- 現代C++編程實戰:132個核心技巧示例(原書第2版)
- Struts 2.x權威指南
- Java EE Web應用開發基礎
- 企業級Java現代化:寫給開發者的云原生簡明指南
- Developing Java Applications with Spring and Spring Boot