Kotlin/基礎語法

維基教科書,自由的教學讀本

基礎語法[編輯]

以下列舉出需要知道的基礎語法,深度的剖析會在之後逐步說明

Package 和 import[編輯]

package my.demo

import kotlin.text.*

// ...

這裏的宣告不一定要完全的合乎資料夾結構,你可以在專案裏任意選擇放置程式碼的位置

程式進入點[編輯]

程式進入點是 main() 函式

fun main() {
    println("Hello world!")
}

注意程式碼結尾不需要加上分號(;)

函式[編輯]

宣告函式的關鍵字是 fun

宣告一個收兩個 Int,並回傳一個 Int的函式

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

只包含 body,隱含回傳型態的寫法

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

沒有有意義回傳值的完整寫法

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

這裏可以把 Unit 省略掉

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


變數[編輯]

只可讀取的常數(value)以 val 宣告,這些常數只能被賦值一次

val a: Int = 1  // 立刻賦值
val b = 2   // 省略 `Int` 型態宣告
val c: Int  // 沒有立刻賦值的話,一定要宣告型態
c = 3       // 延後賦值

可重複賦值的變數(variable)以 var 宣告

var x = 5 // 省略 `Int` 型態宣告
x += 1

Top-level 變數

val PI = 3.14
var x = 0

fun incrementX() { 
    x += 1 
}

註解[編輯]

跟多數語言一樣,Kotlin 支援單行和多行註解

// 這是單行註解

/* 這是一個
多行註解 */

另外也支持巢狀註解

/* The comment starts here
/* contains a nested comment */     
and ends here. */

字串樣板[編輯]

var a = 1
// 樣板內使用變數名稱
val s1 = "a is $a" 

a = 2
// 樣板內使用變數和函式
val s2 = "${s1.replace("is", "was")}, but now is $a"

條件式[編輯]

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

Kotlin 內可以將 if 當作表達式來使用

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


Nullable 和 null 檢查[編輯]

Kotlin 內預設是不允許接收 null 的。如果希望可以接收或者回傳 null 的話,要特別加上「?」標記

比方說,如果 str 不包含數字的話,希望回傳 null 的寫法:

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

使用可能回傳 null 的函式,Kotlin 會自動進行檢查

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

    // 如果不進行檢查就嘗試 `x * y`,因為這兩個變數可能是 null,所以會直接拋出錯誤
    if (x != null && y != null) {
        // x 和 y 經過檢查之後,被標記為非 nullable,所以不會直接拋出錯誤
        println(x * y)
    }
    else {
        println("'$arg1' 或 '$arg2' 不是數字")
    }    
}


或者可以這樣寫

// ...
if (x == null) {
    println("arg1 格式不對:'$arg1'")
    return
}
if (y == null) {
    println("arg2 格式不對:'$arg2'")
    return
}

// x 和 y 經過檢查之後,被標記為非 nullable,所以不會直接拋出錯誤
println(x * y)

型態檢查和自動轉型[編輯]

is 會檢查輸入值是否屬於某個型態。如果某個不變的屬性或者本地變數已經確認過屬於某型態,那麼之後做該型態允許的操作時,就不用再特別做型態轉換的處理:

fun getStringLength(obj: Any): Int? {
    if (obj is String) {
        // `obj` 的型態定義在這裡之後自動轉換為 `String` 
        return obj.length
    }

    // `obj` 在型態檢查之前,還是屬於型態 `Any`
    return null
}

或者可以這樣寫

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

    // `obj` 的型態定義在這裡之後自動轉換為 `String` 
    return obj.length
}

甚至可以這樣寫

fun getStringLength(obj: Any): Int? {
    // `obj` 的型態定義在 `&&` 左邊自動轉換為 `String`
    if (obj is String && obj.length > 0) {
        return obj.length
    }

    return null
}

for[編輯]

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[編輯]

val items = listOf("apple", "banana", "kiwifruit")
var index = 0
while (index < items.size) {
    println("item at $index is ${items[index]}")
    index++
}

when[編輯]

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

範圍(Range)[編輯]

in 來檢查數字是否存在某個範圍內:

val x = 10
val y = 9
if (x in 1..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")
}

在某個範圍裏面迭代:

for (x in 1..5) {
    print(x)
}

或者跳過某幾步:

for (x in 1..10 step 2) {
    print(x)
}
println()
for (x in 9 downTo 0 step 3) {
    print(x)
}

集合[編輯]

在集合裏做迭代:

for (item in items) {
    println(item)
}

in 判斷某物件是否在集合裏面:

when {
    "orange" in items -> println("juicy")
    "apple" in items -> println("apple is fine too")
}

用 lambda 表達式來過濾並重組集合:

val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
fruits
  .filter { it.startsWith("a") }
  .sortedBy { it }
  .map { it.toUpperCase() }
  .forEach { println(it) }

建立基本物件和變數[編輯]

val rectangle = Rectangle(5.0, 2.0)
val triangle = Triangle(3.0, 4.0, 5.0)