1. 程式人生 > >Kotlin基本語法(譯)

Kotlin基本語法(譯)

# 基本語法 ##定義包 軟體包規範應位於原始檔的頂部:
package my.demo

import java.util.*

// ...
不需要匹配目錄和包:原始檔可以任意放在檔案系統中。 ## 定義功能 全Kotlin參考 編輯頁面 基本語法 定義包 軟體包規範應位於原始檔的頂部: package my.demo import java.util.* // … 不需要匹配目錄和包:原始檔可以任意放在檔案系統中。 參見包。 定義功能 具有返回型別的兩個Int引數的Int函式:
//sampleStart
fun sum(a: Int, b: Int): Int {
    return
a + b } //sampleEnd fun main(args: Array<String>) { print("sum of 3 and 5 is ") println(sum(3, 5)) }

函式與表達體和推斷返回型別:

//sampleStart
fun sum(a: Int, b: Int) = a + b
//sampleEnd

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

函式返回無意義值:

//sampleStart
fun printSum(a: Int, b: Int): Unit { println("sum of $a and $b is ${a + b}") } //sampleEnd fun main(args: Array<String>) { printSum(-1, 8) }

Unit 返回型別可以省略:

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

fun main(args: Array<String>)
{ printSum(-1, 8) }
## 定義區域性變數 分配一次(只讀)區域性變數:
fun main(args: Array<String>) {
//sampleStart
    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
//sampleEnd
    println("a = $a, b = $b, c = $c")
}

可變變數:

fun main(args: Array<String>) {
//sampleStart
    var x = 5 // `Int` type is inferred
    x += 1
//sampleEnd
    println("x = $x")
}
## 註釋 就像Java和JavaScript一樣,Kotlin支援行尾和//註釋。
// This is an end-of-line comment

/* This is a block comment
   on multiple lines. */
與Java不同,Kotlin中的塊註釋可以巢狀。 ## 使用字串模板
fun main(args: Array<String>) {
//sampleStart
    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"
//sampleEnd
    println(s2)
}
## 使用條件表示式
//sampleStart
fun maxOf(a: Int, b: Int): Int {
    if (a > b) {
        return a
    } else {
        return b
    }
}
//sampleEnd

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

使用if表示式:

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

fun main(args: Array<String>) {
    println("max of 0 and 42 is ${maxOf(0, 42)}")
}
## 使用可空值並檢查null 當空值可能時,引用必須被明確地標記為可空。 如果不持有整數則返回nullstr:
fun parseInt(str: String): Int? {
    // ...
}
使用返回可空值的函式:
fun parseInt(str: String): Int? {
    return str.toIntOrNull()
}

//sampleStart
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")
    }    
}
//sampleEnd


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)

//sampleStart
    // ...
    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)
//sampleEnd
}

fun main(args: Array<String>) {
    printProduct("6", "7")
    printProduct("a", "7")
    printProduct("99", "b")
}
## 使用型別檢查和自動轉換 這是操作者檢查是否一個表示式是一個型別的一個例項。如果為特定型別檢查不可變的區域性變數或屬性,則不需要顯式轉換:
//sampleStart
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
}
//sampleEnd


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()))
}

或者

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

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


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()))
}

甚至

//sampleStart
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
}
//sampleEnd


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>) {
//sampleStart
    val items = listOf("apple", "banana", "kiwi")
    for (item in items) {
        println(item)
    }
//sampleEnd
}

或者

fun main(args: Array<String>) {
//sampleStart
    val items = listOf("apple", "banana", "kiwi")
    for (index in items.indices) {
        println("item at $index is ${items[index]}")
    }
//sampleEnd
}
## 使用while迴圈
fun main(args: Array<String>) {
//sampleStart
    val items = listOf("apple", "banana", "kiwi")
    var index = 0
    while (index < items.size) {
        println("item at $index is ${items[index]}")
        index++
    }
//sampleEnd
}
##使用when表示式
//sampleStart
fun describe(obj: Any): String =
    when (obj) {
        1          -> "One"
        "Hello"    -> "Greeting"
        is Long    -> "Long"
        !is String -> "Not a string"
        else       -> "Unknown"
    }
//sampleEnd

fun main(args: Array<String>) {
    println(describe(1))
    println(describe("Hello"))
    println(describe(1000L))
    println(describe(2))
    println(describe("other"))
}
##使用範圍 檢查一個數字是使用範圍內操作
fun main(args: Array<String>) {
//sampleStart
    val x = 10
    val y = 9
    if (x in 1..y+1) {
        println("fits in range")
    }
//sampleEnd
}

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

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

迭代一個迴圈:

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

或過程:

fun main(args: Array<String>) {
//sampleStart
    for (x in 1..10 step 2) {
        print(x)
    }
    for (x in 9 downTo 0 step 3) {
        print(x)
    }
//sampleEnd
}
## 使用集合 迭代集合:
fun main(args: Array<String>) {
    val items = listOf("apple", "banana", "kiwi")
//sampleStart
    for (item in items) {
        println(item)
    }
//sampleEnd
}

檢查如果集合包含物件使用in{關鍵詞} 操作:

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

使用lambda表示式過濾和對映集合:

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

原文Kotlin基本語法