美文网首页Kotlin编程
Kotlin笔记 类型检查和转型

Kotlin笔记 类型检查和转型

作者: yangweigbh | 来源:发表于2017-01-19 10:44 被阅读445次

    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笔记 类型检查和转型

        本文链接:https://www.haomeiwen.com/subject/bmqibttx.html