在Java 中 类型转换

  1. public class Fruit {
  2. private String color;
  3. }
  4. public class Banana extends Fruit {
  5. private String color;
  6. public Banana(String color) {
  7. this.color = color;
  8. }
  9. public String getColor() {
  10. return color;
  11. }
  12. public static void main(String[] args) {
  13. Fruit fruit = new Banana("yellow");
  14. if (fruit instanceof Banana) {
  15. Banana banana = (Banana) fruit;
  16. System.out.println(banana.getColor());
  17. }
  18. }
  19. }
  • 比较麻烦
fun main() {
    val fruit: Fruit = Banana("green")

    if (fruit is Banana) {
        println(fruit.color)
    }
    //fruit.color// 没有用 is 判断不能直接调用
}
  • kotlin is 判断后,类型自动转换

强制转换作用范围

智能类型转换 - 图1

    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)