- 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.
推薦閱讀
- 算法訓練營:入門篇(全彩版)
- Building Mobile Applications Using Kendo UI Mobile and ASP.NET Web API
- SQL經典實例(第2版)
- 機器學習與R語言實戰
- 0 bug:C/C++商用工程之道
- Android傳感器開發與智能設備案例實戰
- 寫給程序員的Python教程
- Visual Basic程序設計(第三版)
- Python Programming for Arduino
- 深度學習程序設計實戰
- Python 快速入門(第3版)
- 你真的會寫代碼嗎
- Raspberry Pi Robotic Projects
- Java EE基礎實用教程
- Django 3 Web Development Cookbook