1.is运算符和 !is 运算符
kotlin中API提供的 is 运算符相似于Java中的 instanceof 关键字的用法。is 运算符能够检查对象是否与特定的类型兼容(兼容:此对象是该类型,或者派生类),同时也用来检查对象(变量)是否属于某数据类型(如Int、String、Boolean等)。 !is运算符是它的否认形式。java
val mAccount = "秦川小将"
println(mAccount is String)
输出:web
truesvg
val mAccount = "秦川小将"
println(mAccount !is String)
输出:ui
falsespa
2.as运算符和as?运算符
as运算符用于执行引用类型的显式类型转换。若是要转换的类型与指定的类型兼容,转换就会成功进行;若是类型不兼容,使用as?运算符就会返回值null。在Kotlin中,父类是禁止转换为子类型的。.net
open class Fruit
open class Apple(name: String) : Fruit()
//
val mFruit = Fruit()
val mApple = Apple("苹果")
//
println(mFruit as Apple)
上面这种用法会报:java.lang.ClassCastException异常code
open class Fruit
open class Apple(name: String) : Fruit()
//
val mFruit = Fruit()
val mApple = Apple("苹果")
//
println(mFruit as? Apple)
输出:xml
null对象
open class Fruit
open class Apple(name: String) : Fruit()
//
val mFruit = Fruit()
val mApple = Apple("苹果")
//
println(mApple as Fruit)
输出:get
Apple@1d81eb93
父类转换为子类是对OOP的严重违反,不推荐使用,父类是不能转换为子类的,子类包含了父类全部的方法和属性,而父类则未必具备和子类一样成员范围,因此这种转换是不被容许的,即使是两个具备父子关系的空类型,也是如此。
本文分享 CSDN - 秦川小将。
若有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一块儿分享。