在Java 中 类型转换
public class Fruit {
private String color;
}
public class Banana extends Fruit {
private String color;
public Banana(String color) {
this.color = color;
}
public String getColor() {
return color;
}
public static void main(String[] args) {
Fruit fruit = new Banana("yellow");
if (fruit instanceof Banana) {
Banana banana = (Banana) fruit;
System.out.println(banana.getColor());
}
}
}
- 比较麻烦
fun main() {
val fruit: Fruit = Banana("green")
if (fruit is Banana) {
println(fruit.color)
}
//fruit.color// 没有用 is 判断不能直接调用
}
- kotlin is 判断后,类型自动转换
强制转换作用范围
var x: String? = "hello"
if (x != null) {
println(x.length) //类型 String (Smart cast to kotlin.String)
}
val length = x.length //类型 String?
- 在if 判断非空内,kotlin 智能帮我们转换了非空类型。
不支持智能转换的情况
var y: String? = "welcome"
fun main() {
if (y != null) {
println(y.length) //IDE报错提示
}
}
- Smart cast to ‘String’ is impossible, because ‘y’ is a mutable property that could have been changed by this time
- 为什么?因为y是可变的,有可能其他地方如线程修改了它
- 可使用 val 定义 y
类型安全转换 as?
当as 转换失败返回 null 而不是抛异常
val fruit: Fruit = Banana("green")
println((fruit as? Person)?.title)