美文网首页
Kotlin介绍系列(二)基本语法(2)

Kotlin介绍系列(二)基本语法(2)

作者: Phoobobo | 来源:发表于2017-10-11 00:01 被阅读29次

is(反义是!is)与自动类型转换

is操作符是用来判断一个对象是否是一个类型的实例

fun getStringLength(obj: Any): Int? {
    if (obj is String) {
        // `obj` is automatically cast to `String` in this branch
        return obj.length
    }
    // `obj` is still of type `Any` outside of the type-checked branch
    return null
}

从上面的例子可以看出,经过is进行类型检查以后,就没有必要进行类型转换了,对象会自动转换成被检查的类型。

when——一个更优秀的switch替代品

when结构里的判断项相当的灵活,可以是一个常量,也可以是表达式(函数,类型检查,范围等)。举例说明:

when (x) {
    0, 1 -> print("x == 0 or x == 1")
    2 -> print("x ==2")
    else -> print("otherwise")
}
when (x) {
    in 1..10 -> print("x is in the range")
    in validNumbers -> print("x is valid")
    !in 10..20 -> print("x is outside the range")
    else -> print("none of the above")
}
fun hasPrefix(x: Any) = when(x) {
    is String -> x.startsWith("prefix")
    else -> false
}

when还可以用作多重if/else选择的替代:

when {
    x.isOdd() -> print("x is odd")
    x.isEven() -> print("x is even")
    else -> print("x is funny")
}

Kotlin介绍系列(二)基本语法(3)

相关文章

网友评论

      本文标题:Kotlin介绍系列(二)基本语法(2)

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