Kotlin基本语法

译自Kotlin Basic Syntax

定义包

软件包定义(Package specification)应位于源文件的顶部:

package my.demo

import java.util.*

// ...

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

参见包(Packages) 。

定义函数

具有Int返回类型的两个Int参数的函数:

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

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

具有表达体(expression body)和推断返回类型(inferred return type)的函数:

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

fun main(args: Array) {
    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) {
    printSum(-1, 8)
}

Unit返回类型可以省略:

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

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

请参阅函数(Functions) 。

定义局部变量

赋值一次(只读)(Assign-once (read-only))局部变量:

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

可变(Mutable)变量:

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

另请参见属性和字段 (Properties And Fields)。

注释

就像Java和JavaScript一样,Kotlin支持行尾和块注释。

// This is an end-of-line comment

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

与Java不同,Kotlin中的块注释可以嵌套。

有关文档注释语法的信息,请参阅注释Kotlin代码 (Documenting Kotlin Code )。

使用字符串模板

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

请参阅String模板 (String templates)。

使用条件表达式

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

fun main(args: Array) {
    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) {
    println("max of 0 and 42 is ${maxOf(0, 42)}")
}

查看if-expressions。

使用可空值(nullable values)并检查null

当空值可能时,引用必须被明确地标记为可空(explicitly marked as nullable when null value is possible) 。

如果str不包含整数,则返回null :

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

使用返回可空值的函数:

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) {
    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) {
    printProduct("6", "7")
    printProduct("a", "7")
    printProduct("99", "b")
}

见空安全(Null-safety) 。

使用类型检查和自动转换

is运算符检查表达式是否是类型的实例。 如果检查不可变(immutable)局部变量或属性为特定类型,则不需要显式转换:

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

请参阅类(Classes)和类型转换 (Type casts)。

使用for循环

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

要么

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

参见for循环(for loop) 。

使用while循环

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

看到while循环 (while loop)。

表达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) {
    println(describe(1))
    println(describe("Hello"))
    println(describe(1000L))
    println(describe(2))
    println(describe("other"))
}

看when表达式(when expression)。

使用范围

使用in操作符检查数字是否在范围内:

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

检查一个数字是否超出范围:

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

在一个范围内迭代:

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

或过程(progression):

fun main(args: Array) {
    for (x in 1..10 step 2) {
        print(x)
    }
    for (x in 9 downTo 0 step 3) {
        print(x)
    }
}

见范围(Ranges) 。

使用集合

在一个集合内迭代:

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

使用in运算符检查集合是否包含一个对象:

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

使用lambda表达式过滤和映射集合(filter and map collections):

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

请参阅高阶函数和Lambdas(Higher-order functions and Lambdas) 。

你可能感兴趣的:(Kotlin基本语法)