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

575 阅读2分钟

使用类型检测及自动类型转换

is 运算符检测一个表达式是否某类型的一个实例。 如果一个不可变的局部变量或属性已经判断出为某类型,那么检测后的分支中可以直接当作该类型使用,无需显式转换。

fun getStringLength(obj: Any): Int? {
    if (obj is String) {
        // `obj` 在该条件分支内自动转换成 `String`
        return obj.length
    }

    // 在离开类型检测分支后,`obj` 仍然是 `Any` 类型
    return null
}

使用 for 循环

for 循环可以对任何提供迭代器(iterator)的对象进行遍历,这相当于像 C# 这样的语言中的 foreach 循环。语法如下

for (item in collection) print(item)

或者

val items = listOf("apple", "banana", "kiwifruit")
for (item in items) {
    println(item)
}

亦或是

val items = listOf("apple", "banana", "kiwifruit")
for (index in items.indices) {
    println("item at $index is ${items[index]}")
}

使用 while 表达式

使用 while

while (x > 0) {
    x--
}

或者 do..while

do {
  val y = retrieveData()
} while (y != null) // y 在此处可见

使用 when 表达式

when 取代了类 C 语言的 switch 操作符。其最简单的形式如下

when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> { // 注意这个块
        print("x is neither 1 nor 2")
    }
}

如果很多分支需要用相同的方式处理,则可以把多个分支条件放在一起,用逗号分隔

when (x) {
    0, 1 -> print("x == 0 or x == 1")
    else -> print("otherwise")
}

我们可以用任意表达式(而不只是常量)作为分支条件

when (x) {
    parseInt(s) -> print("s encodes x")
    else -> print("s does not encode x")
}

使用区间(range)

使用 in 运算符来检测某个数字是否在指定区间内

val x = 10
val y = 9
if (x in 1..y+1) { //等同于 x >=1 && x <=y+1
    println("fits in range")
}

检测某个数字是否在指定区间外

val list = listOf("a", "b", "c")

if (-1 !in 0..list.lastIndex) {
    println("-1 is out of range")
}
if (list.size !in list.indices) {
    println("list size is out of valid list indices range, too")
}

要以相反的顺序迭代数字,使用 downTo 函数

for(i in 4 downTo 1) print (i)

也可以用任意步骤(不一定是1)迭代数字。这是通过该 step 功能完成的

    for (i in 1 ... 8 step 2) print(i)
    println()
    for (i in 8 downTo 1 step 2) print(i)
}

输出为

1357
8642

要迭代不包含其end元素的数字范围

for(i in 1 to 10){ //i 从 1 到 10,10 被排除在外
    print(i)
}