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

使用類型檢測及自動類型轉換

is 運算符檢測一個表達式是否某類型的一個實例。 若是一個不可變的局部變量或屬性已經判斷出爲某類型,那麼檢測後的分支中能夠直接看成該類型使用,無需顯式轉換。bash

fun getStringLength(obj: Any): Int? {
    if (obj is String) {
        // `obj` 在該條件分支內自動轉換成 `String`
        return obj.length
    }

    // 在離開類型檢測分支後,`obj` 仍然是 `Any` 類型
    return null
}

複製代碼

使用 for 循環

for 循環能夠對任何提供迭代器(iterator)的對象進行遍歷,這至關於像 C# 這樣的語言中的 foreach 循環。語法以下app

for (item in collection) print(item)
複製代碼

或者函數

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

亦或是ui

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

使用 while 表達式

使用 whilespa

while (x > 0) {
    x--
}
複製代碼

或者 do..whilecode

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")
    }
}
複製代碼

若是不少分支須要用相同的方式處理,則能夠把多個分支條件放在一塊兒,用逗號分隔get

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

咱們能夠用任意表達式(而不僅是常量)做爲分支條件string

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

使用區間(range)

使用 in 運算符來檢測某個數字是否在指定區間內it

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)
}
複製代碼
相關文章
相關標籤/搜索