Kotlin笔记 类型检查和转型

is and !is 操作符

is!is可以用来检查一个实例是否属于一种类型

if (obj is String) {
    print(obj.length)
}

if (obj !is String) { // same as !(obj is String)
    print("Not a String")
}
else {
    print(obj.length)
}

Kotlin里经过is检查的变量不用显示的转型(自动转换)

fun demo(x: Any) {
    if (x is String) {
        print(x.length) // x is automatically cast to String
    }
}

或者

if (x !is String) return
    print(x.length) // x is automatically cast to String

或者

&& 和 || 的右边

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

    // x is automatically cast to string on the right-hand side of `&&`
    if (x is String && x.length > 0) {
        print(x.length) // x is automatically cast to String
    }

或者when里

when (x) {
    is Int -> print(x + 1)
    is String -> print(x.length + 1)
    is IntArray -> print(x.sum())
}

如果变量check和usage之间,编译器无法保证变量不变,则不会做自动转换

  • val local variable
  • val properties
  • var local variable
  • var properties

as操作符

通过as转型失败时会抛出异常,as?转型失败会返回null

val x: String = y as String

val x: String? = y as? String

你可能感兴趣的:(Kotlin笔记 类型检查和转型)