官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 咸丰县| 合川市| 台东市| 昌江| 渝中区| 鱼台县| 夏津县| 苏尼特左旗| 青铜峡市| 清涧县| 威信县| 涿州市| 永丰县| 永兴县| 大姚县| 柞水县| 旺苍县| 佛冈县| 昆山市| 大宁县| 洛浦县| 麻栗坡县| 剑川县| 扶沟县| 长葛市| 江山市| 河北区| 会泽县| 柞水县| 上虞市| 大厂| 多伦县| 岳西县| 建宁县| 桐乡市| 肥西县| 望江县| 吉安县| 迁安市| 息烽县| 舞钢市|