- 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.
推薦閱讀
- ThinkPHP 5實戰(zhàn)
- AIRAndroid應用開發(fā)實戰(zhàn)
- HTML5+CSS3網(wǎng)站設(shè)計基礎(chǔ)教程
- Java 11 Cookbook
- The HTML and CSS Workshop
- H5頁面設(shè)計:Mugeda版(微課版)
- Salesforce Reporting and Dashboards
- Java實戰(zhàn)(第2版)
- GameMaker Essentials
- C語言程序設(shè)計簡明教程:Qt實戰(zhàn)
- TypeScript 2.x By Example
- Visual Basic程序設(shè)計全程指南
- PhoneGap 4 Mobile Application Development Cookbook
- Learning ECMAScript 6
- Java EE基礎(chǔ)實用教程