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

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.

主站蜘蛛池模板: 永州市| 太康县| 阳信县| 定结县| 安新县| 兴和县| 昌图县| 大庆市| 南木林县| 巴林左旗| 永福县| 吉林市| 西乌| 仙桃市| 五指山市| 双城市| 丘北县| 淄博市| 玉龙| 长沙县| 达日县| 河南省| 邓州市| 德钦县| 凉山| 安福县| 建德市| 昌宁县| 深水埗区| 贺州市| 司法| 漯河市| 三原县| 门头沟区| 葫芦岛市| 瓦房店市| 绥滨县| 微博| 保山市| 于田县| 西青区|