is !is 表达式

在很多情形中,需要使用非明确的类型,因为编译器会跟踪 检查静态变量,并在需要的时候自动插入安全转换:

  1. fun demo(x: Any) {
  2. print(x.length) // x is automatically cast to String
  3. }
  4. }

编译器足够智能如何转换是安全的,如果不安全将会返回:

  1. // x is automatically cast to string on the right-hand side of `||`
  2. if (x !is String || x.length == 0) return
  3. // x is automatically cast to string on the right-hand side of `&&`
  4. print(x.length) // x is automatically cast to String

这样的转换在 when 表达式和 whie 循环中也会发生

如果转换是不被允许的那么转换符就会抛出一个异常。因此我们称之为不安全的。在kotlin 中 我们用前缀 as 操作符

  1. val x: String = y as String

为了 java 的转换语句匹配我们得像下面这样:

为了避免抛出异常,可以用 as? 这个安全转换符,这样失败就会返回 null :