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

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.

主站蜘蛛池模板: 平舆县| 榆树市| 伊金霍洛旗| 衢州市| 忻城县| 铅山县| 象山县| 漯河市| 乌兰察布市| 秦皇岛市| 疏附县| 松潘县| 安溪县| 温泉县| 芜湖县| 灌阳县| 沐川县| 疏勒县| 绥芬河市| 乐昌市| 思南县| 河北省| 寿光市| 合江县| 新竹县| 刚察县| 辽阳市| 宿州市| 尚志市| 文水县| 曲沃县| 棋牌| 深水埗区| 石河子市| 安化县| 怀宁县| 盘锦市| 新晃| 江孜县| 肇东市| 德阳市|