Kotlin基礎語法

定義包

定義包的規範應位於源文件的頂部:

package com.yiibai

import java.util.*

// ...

不需要匹配目錄和包:源文件可以任意放在文件系統中。

有關包的詳細用法,請參考:http://www.yiibai.com/kotlin/packages.html

定義函數

具有返回Int類型的兩個Int參數的函數:

fun sum(a: Int, b: Int): Int {
    return a + b
}

fun main(args: Array<String>) {
    print("sum of 3 and 5 is ")
    println(sum(3, 5))
}

函數與表達主體和推斷返回值的類型:

fun sum(a: Int, b: Int) = a + b

fun main(args: Array<String>) {
    println("sum of 19 and 23 is ${sum(19, 23)}")
}

函數返回無意義值:

fun printSum(a: Int, b: Int): Unit {
    println("sum of $a and $b is ${a + b}")
}

fun main(args: Array<String>) {
    printSum(-1, 8)
}

Unit返回類型可以省略:

fun printSum(a: Int, b: Int) {
    println("sum of $a and $b is ${a + b}")
}

fun main(args: Array<String>) {
    printSum(-1, 8)
}

有關函數的詳細用法,請參考:http://www.yiibai.com/kotlin/functions.html

定義局部變量

分配一次(只讀)局部變量:

fun main(args: Array<String>) {
    val a: Int = 1  // immediate assignment
    val b = 2   // `Int` type is inferred
    val c: Int  // Type required when no initializer is provided
    c = 3       // deferred assignment
    println("a = $a, b = $b, c = $c")
}

可變變量:

fun main(args: Array<String>) {
    var x = 5 // `Int` type is inferred
    x += 1
    println("x = $x")
}

變量還可作爲屬性和字段來使用,另請參考: http://www.yiibai.com/kotlin/properties.html

Kotlin的註釋

Kotlin中的註釋類似於Java和JavaScript,Kotlin支持行尾和塊註釋。

// This is an end-of-line comment

/* This is a block comment
   on multiple lines. */

與Java不同的是,Kotlin中的塊註釋可以嵌套。

有關文檔註釋語法的信息,請參閱文檔Kotlin代碼: http://www.yiibai.com/kotlin/kotlin-doc.html

使用字符串模板

fun main(args: Array<String>) {
    var a = 1
    // simple name in template:
    val s1 = "a is $a" 

    a = 2
    // arbitrary expression in template:
    val s2 = "${s1.replace("is", "was")}, but now is $a"
    println(s2)
}

有關於字符串模板的更多信息,請參考: http://www.yiibai.com/kotlin/basic-types.html

使用條件表達式

fun maxOf(a: Int, b: Int): Int {
    if (a > b) {
        return a
    } else {
        return b
    }
}

fun main(args: Array<String>) {
    println("max of 0 and 42 is ${maxOf(0, 42)}")
}

使用if表達式:

fun maxOf(a: Int, b: Int) = if (a > b) a else b

fun main(args: Array<String>) {
    println("max of 0 and 42 is ${maxOf(0, 42)}")
}

有關於if表達式的更多信息,請參考: http://www.yiibai.com/kotlin/control-flow.html#if-expression

使用可空值來檢查null值

當可能爲null值時,引用必須被明確地標記爲可空(null)。

如果str不包含整數,則返回null

fun parseInt(str: String): Int? {
    // ...
}

使用可返回null值的函數:

fun parseInt(str: String): Int? {
    return str.toIntOrNull()
}

fun printProduct(arg1: String, arg2: String) {
    val x = parseInt(arg1)
    val y = parseInt(arg2)

    // Using `x * y` yields error because they may hold nulls.
    if (x != null && y != null) {
        // x and y are automatically cast to non-nullable after null check
        println(x * y)
    }
    else {
        println("either '$arg1' or '$arg2' is not a number")
    }    
}


fun main(args: Array<String>) {
    printProduct("6", "7")
    printProduct("a", "7")
    printProduct("a", "b")
}

上面代碼,也可以編寫成下面 -

fun parseInt(str: String): Int? {
    return str.toIntOrNull()
}

fun printProduct(arg1: String, arg2: String) {
    val x = parseInt(arg1)
    val y = parseInt(arg2)

    // ...
    if (x == null) {
        println("Wrong number format in arg1: '${arg1}'")
        return
    }
    if (y == null) {
        println("Wrong number format in arg2: '${arg2}'")
        return
    }

    // x and y are automatically cast to non-nullable after null check
    println(x * y)
}

fun main(args: Array<String>) {
    printProduct("6", "7")
    printProduct("a", "7")
    printProduct("99", "b")
}

有關於可null值的更多信息,請參考:http://www.yiibai.com/kotlin/null-safety.html

使用類型檢查和自動轉換

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
}


fun main(args: Array<String>) {
    fun printLength(obj: Any) {
        println("'$obj' string length is ${getStringLength(obj) ?: "... err, not a string"} ")
    }
    printLength("Incomprehensibilities")
    printLength(1000)
    printLength(listOf(Any()))
}

上面代碼,也可以編寫成下面 -

fun getStringLength(obj: Any): Int? {
    if (obj !is String) return null

    // `obj` is automatically cast to `String` in this branch
    return obj.length
}


fun main(args: Array<String>) {
    fun printLength(obj: Any) {
        println("'$obj' string length is ${getStringLength(obj) ?: "... err, not a string"} ")
    }
    printLength("Incomprehensibilities")
    printLength(1000)
    printLength(listOf(Any()))
}

上面代碼,還可以編寫成下面 -

fun getStringLength(obj: Any): Int? {
    // `obj` is automatically cast to `String` on the right-hand side of `&&`
    if (obj is String && obj.length > 0) {
        return obj.length
    }

    return null
}


fun main(args: Array<String>) {
    fun printLength(obj: Any) {
        println("'$obj' string length is ${getStringLength(obj) ?: "... err, is empty or not a string at all"} ")
    }
    printLength("Incomprehensibilities")
    printLength("")
    printLength(1000)
}

可以從這裏瞭解上面提及的兩個概念: 類和類型轉換 。

使用for循環

fun main(args: Array<String>) {
    val items = listOf("apple", "banana", "kiwi")
    for (item in items) {
        println(item)
    }
}

上面代碼,可以編寫成如下 -

fun main(args: Array<String>) {
    val items = listOf("apple", "banana", "kiwi")
    for (index in items.indices) {
        println("item at $index is ${items[index]}")
    }
}

有關於for循環的更多信息,請參考: http://www.yiibai.com/kotlin/control-flow.html#for-loops

使用 while 循環

fun main(args: Array<String>) {
    val items = listOf("apple", "banana", "kiwi")
    var index = 0
    while (index < items.size) {
        println("item at $index is ${items[index]}")
        index++
    }
}

有關於while循環的更多信息,請參考: http://www.yiibai.com/kotlin/control-flow.html#while-loops

使用 when 表達式

fun describe(obj: Any): String =
when (obj) {
    1          -> "One"
    "Hello"    -> "Greeting"
    is Long    -> "Long"
    !is String -> "Not a string"
    else       -> "Unknown"
}

fun main(args: Array<String>) {
    println(describe(1))
    println(describe("Hello"))
    println(describe(1000L))
    println(describe(2))
    println(describe("other"))
}

有關於when表達式的更多信息,請參考: http://www.yiibai.com/kotlin/control-flow.html#when-expression

使用範圍

使用in操作符檢查數字是否在指定範圍內:

fun main(args: Array<String>) {
    val x = 10
    val y = 9
    if (x in 1..y+1) {
        println("fits in range")
    }
}

檢查一個數字是否超出指定範圍:

fun main(args: Array<String>) {
    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")
    }
}

上面代碼,執行結果如下 -

-1 is out of range
list size is out of valid list indices range too

迭代範圍:

fun main(args: Array<String>) {
    for (x in 1..5) {
        print(x)
    }
}

或過程:

fun main(args: Array<String>) {
    for (x in 1..10 step 2) {
        println(x)
    }
    println("===============================")
    for (x in 9 downTo 0 step 3) {
        println(x)
    }
}

上面代碼,執行結果如下 -

1
3
5
7
9
===============================
9
6
3
0

有關於範圍的更多信息,請參考:http://www.yiibai.com/kotlin/ranges.html

使用集合

迭代集合:

fun main(args: Array<String>) {
    val items = listOf("apple", "banana", "kiwi")
    for (item in items) {
        println(item)
    }
}

檢查集合是否包含一個對象,使用in運算符:

fun main(args: Array<String>) {
    val items = setOf("apple", "banana", "kiwi")
    when {
        "orange" in items -> println("juicy")
        "apple" in items -> println("apple is fine too")
    }
}

使用lambda表達式過濾映射集合:

fun main(args: Array<String>) {
    val fruits = listOf("banana", "avocado", "apple", "kiwi")
    fruits
    .filter { it.startsWith("a") }
    .sortedBy { it }
    .map { it.toUpperCase() }
    .forEach { println(it) }
}

有關於高階函數和Lambda的更多信息,請參考:http://www.yiibai.com/kotlin/lambdas.html