# 基本语法概述 本章会通过示例程序向你介绍 Kotlin 的一系列基本语法元素. 在各节的末尾, 你可以找到各个专题详细信息的页面链接. 你也可以通过 JetBrains Academy 的免费 [Kotlin 核心课程](https://hyperskill.org/tracks?category=4&utm_source=jbkotlin_hs&utm_medium=referral&utm_campaign=kotlinlang-docs&utm_content=button_1&utm_term=22.03.23) 学习 Kotlin 的全部基本知识. ## 包的定义与导入 包的定义应该在源代码文件的最上方: ```KOTLIN package my.demo import kotlin.text.* // ... ``` 源代码所在的目录结构不必与包结构保持一致: 源代码文件可以放置在文件系统的任意位置. 参见 [包](packages.html). ## 程序入口点(entry point) Kotlin 应用程序的入口点是 `main` 函数: ```KOTLIN fun main() { println("Hello world!") } ``` `main` 函数的另一种形式可以接受数量不定的 `String` 参数: ```KOTLIN fun main(args: Array) { println(args.contentToString()) } ``` ## 向标准输出(Standard Output)打印信息 `print` 函数会将传递给它的参数打印到标准输出(Standard Output): ```KOTLIN fun main() { //sampleStart print("Hello ") print("world!") //sampleEnd } ``` `println` 函数会打印它的参数, 并在末尾加上换行(Line Break), 因此之后的打印信息会出现在下一行: ```KOTLIN fun main() { //sampleStart println("Hello world!") println(42) //sampleEnd } ``` ## 从标准输入(Standard Input)读取信息 `readln()` 函数会从标准输入(Standard Input)读取信息. 这个函数将用户输入的整个行读取为字符串. 你可以使用 `println()`, `readln()`, 和 `print()` 函数, 打印消息, 要求用户输入, 并显示用户输入的内容: ```KOTLIN // 打印消息, 要求用户输入 println("Enter any word: ") // 读取并保存用户的输入. 例如: Happiness val yourWord = readln() // 将用户的输入和一个消息一起打印输出 print("You entered the word: ") print(yourWord) // 输出结果为 You entered the word: Happiness ``` 更多详情请参见 [读取标准输入](read-standard-input.html). ## 函数 以下函数接受两个 `Int` 类型参数, 并返回 `Int` 类型结果: ```KOTLIN //sampleStart fun sum(a: Int, b: Int): Int { return a + b } //sampleEnd fun main() { print("sum of 3 and 5 is ") println(sum(3, 5)) } ``` 以下函数使用表达式语句作为函数体, 返回类型由自动推断决定: ```KOTLIN //sampleStart fun sum(a: Int, b: Int) = a + b //sampleEnd fun main() { println("sum of 19 and 23 is ${sum(19, 23)}") } ``` 以下函数不返回有意义的结果: ```KOTLIN //sampleStart fun printSum(a: Int, b: Int): Unit { println("sum of $a and $b is ${a + b}") } //sampleEnd fun main() { printSum(-1, 8) } ``` 返回值为 `Unit` 类型时, 可以省略: ```KOTLIN //sampleStart fun printSum(a: Int, b: Int) { println("sum of $a and $b is ${a + b}") } //sampleEnd fun main() { printSum(-1, 8) } ``` 参见 [函数](functions.html). ## 变量 在 Kotlin 中, 声明变量时以关键字, `val` 或 `var` 开始, 之后是变量名称. 使用 `val` 关键字声明的变量只能赋值一次. 这是不可变的, 只读的局部变量, 在初始化之后就不能再次给它设定不同的值: ```KOTLIN fun main() { //sampleStart // 声明变量 x, 并初始化赋值为 5 val x: Int = 5 // 输出结果为 5 //sampleEnd println(x) } ``` 使用关键字 `var` 声明的变量可以多次赋值. 这是可变的变量, 在初始化之后也可以改变它的值: ```KOTLIN fun main() { //sampleStart // 声明变量 x, 并初始化赋值为 5 var x: Int = 5 // 将新的值 6 赋值给变量 x x += 1 // 输出结果为 6 //sampleEnd println(x) } ``` Kotlin 支持类型推断, 能够自动识别声明的变量的数据类型. 在声明一个变量时, 你可以省略变量名之后的类型: ```KOTLIN fun main() { //sampleStart // 声明变量 x, 赋值为 5; 变量类型自动推断为 `Int` val x = 5 // 5 //sampleEnd println(x) } ``` 变量只有在初始化之后才能使用. 可以在变量声明时初始化, 也可以先声明变量, 以后再初始化. 后一种情况下, 必须指明数据类型: ```KOTLIN fun main() { //sampleStart // 在声明变量 x 时初始化; 不需要指定类型 val x = 5 // 声明变量 c, 不初始化; 需要指定类型 val c: Int // 在声明变量 c 之后再初始化 c = 3 // 5 // 3 //sampleEnd println(x) println(c) } ``` 也可以将变量声明在顶级(top level): ```KOTLIN //sampleStart val PI = 3.14 var x = 0 fun incrementX() { x += 1 } // x = 0; PI = 3.14 // incrementX() // x = 1; PI = 3.14 //sampleEnd fun main() { println("x = $x; PI = $PI") incrementX() println("incrementX()") println("x = $x; PI = $PI") } ``` 关于属性的声明, 更多详情请参见 [属性(Property)](properties.html). ## 创建类与实例 要定义类, 请使用 `class` 关键字: ```KOTLIN class Shape ``` 类的属性(Property)可以在类声明部分或类主体部分中列出: ```KOTLIN class Rectangle(val height: Double, val length: Double) { val perimeter = (height + length) * 2 } ``` 会自动生成一个默认构造器, 参数是在类声明部分中定义的那些属性: ```KOTLIN class Rectangle(val height: Double, val length: Double) { val perimeter = (height + length) * 2 } fun main() { val rectangle = Rectangle(5.0, 2.0) println("The perimeter is ${rectangle.perimeter}") } ``` 类之间的继承关系使用冒号(`:`)表示. 类默认为 `final`; 要允许一个类被后代继承, 请将它标记为 `open`: ```KOTLIN open class Shape class Rectangle(val height: Double, val length: Double): Shape() { val perimeter = (height + length) * 2 } ``` 关于构造器与继承, 更多详情请参见 [类](classes.html) 和 [对象与实例](object-declarations.html). ## 注释 与大多数现代编程语言一样, Kotlin 支持单行(或者叫做 行尾)注释, 也支持多行 (或者叫做 块) 注释: ```KOTLIN // 这是一条行尾注释 /* 这是一条块注释 可以包含多行内容. */ ``` Kotlin 的块注释允许嵌套: ```KOTLIN /* 注释从这里开始 /* 包含一个嵌套的注释 */ 到这里结束. */ ``` 关于文档注释的语法, 详情请参见 [Kotlin 代码中的文档](kotlin-doc.html). ## 字符串模板 ```KOTLIN fun main() { //sampleStart var a = 1 // 在字符串模板内使用简单的变量名称 val s1 = "a is $a" a = 2 // 在字符串模板内使用任意的表达式: val s2 = "${s1.replace("is", "was")}, but now is $a" //sampleEnd println(s2) } ``` 详情请参见 [字符串模板](strings.html#string-templates). ## 条件表达式 ```KOTLIN //sampleStart fun maxOf(a: Int, b: Int): Int { if (a > b) { return a } else { return b } } //sampleEnd fun main() { println("max of 0 and 42 is ${maxOf(0, 42)}") } ``` 在 Kotlin 中, `if` 也可以用作表达式: ```KOTLIN //sampleStart fun maxOf(a: Int, b: Int) = if (a > b) a else b //sampleEnd fun main() { println("max of 0 and 42 is ${maxOf(0, 42)}") } ``` 参见 [if 表达式](control-flow.html#if-expression). ## for 循环 ```KOTLIN fun main() { //sampleStart val items = listOf("apple", "banana", "kiwifruit") for (item in items) { println(item) } //sampleEnd } ``` 或者: ```KOTLIN fun main() { //sampleStart val items = listOf("apple", "banana", "kiwifruit") for (index in items.indices) { println("item at $index is ${items[index]}") } //sampleEnd } ``` 参见 [for 循环](control-flow.html#for-loops). ## while 循环 ```KOTLIN fun main() { //sampleStart val items = listOf("apple", "banana", "kiwifruit") var index = 0 while (index < items.size) { println("item at $index is ${items[index]}") index++ } //sampleEnd } ``` 参见 [while 循环](control-flow.html#while-loops). ## when 表达式 ```KOTLIN //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() { println(describe(1)) println(describe("Hello")) println(describe(1000L)) println(describe(2)) println(describe("other")) } ``` 参见 [when 表达式和语句](control-flow.html#when-expressions-and-statements). ## 值范围(Range) 使用 `in` 操作符检查一个数值是否在某个值范围(Range)之内: ```KOTLIN fun main() { //sampleStart val x = 10 val y = 9 if (x in 1..y+1) { println("fits in range") } //sampleEnd } ``` 检查一个数值是否在某个值范围之外: ```KOTLIN fun main() { //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 } ``` 在一个值范围内进行遍历迭代: ```KOTLIN fun main() { //sampleStart for (x in 1..5) { print(x) } //sampleEnd } ``` 或者, 在一个数列(progression)上进行遍历迭代: ```KOTLIN fun main() { //sampleStart for (x in 1..10 step 2) { print(x) } println() for (x in 9 downTo 0 step 3) { print(x) } //sampleEnd } ``` 参见 [值范围(Range)与数列(Progression)](ranges.html). ## 集合(Collection) 在一个集合上进行遍历迭代: ```KOTLIN fun main() { val items = listOf("apple", "banana", "kiwifruit") //sampleStart for (item in items) { println(item) } //sampleEnd } ``` 使用 `in` 运算符检查一个集合是否包含某个对象: ```KOTLIN fun main() { val items = setOf("apple", "banana", "kiwifruit") //sampleStart when { "orange" in items -> println("juicy") "apple" in items -> println("apple is fine too") } //sampleEnd } ``` 使用 [Lambda 表达式](lambdas.html) 对集合元素进行过滤和变换: ```KOTLIN fun main() { //sampleStart val fruits = listOf("banana", "avocado", "apple", "kiwifruit") fruits .filter { it.startsWith("a") } .sortedBy { it } .map { it.uppercase() } .forEach { println(it) } //sampleEnd } ``` 参见 [集合(Collection)概述](collections-overview.html). ## 可为 null 的值与 null 值检查 当一个引用可能为 `null` 值时, 对应的类型声明必须明确地标记为可为 null. 类型名称末尾带 `?` 符号表示可为 null 值. 例如, `Int?`. 当 `str` 中的字符串内容不是一个整数时, 返回 `null`: ```KOTLIN fun parseInt(str: String): Int? { return str.toIntOrNull() } ``` 以下示例演示如何使用一个返回值可为 null 的函数: ```KOTLIN fun parseInt(str: String): Int? { return str.toIntOrNull() } //sampleStart fun printProduct(arg1: String, arg2: String) { val x = parseInt(arg1) val y = parseInt(arg2) // 直接使用 `x * y` 会导致错误, 因为它们可能为 null. if (x != null && y != null) { // 在进行过 null 值检查之后, x 和 y 的类型会被自动转换为非 null 变量 println(x * y) } else { println("'$arg1' or '$arg2' is not a number") } } //sampleEnd fun main() { printProduct("6", "7") printProduct("a", "7") printProduct("a", "b") } ``` 或者: ```KOTLIN 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 } // 在进行过 null 值检查之后, x 和 y 的类型会被自动转换为非 null 变量 println(x * y) //sampleEnd } fun main() { printProduct("6", "7") printProduct("a", "7") printProduct("99", "b") } ``` 参见 [Null 值安全](null-safety.html). ## 类型检查与自动类型转换 `is` 运算符可以检查一个表达式的值是不是某个类型的实例. 如果对一个不可变的局部变量或属性进行过类型检查, 那么之后的代码就不必再对它进行显式地类型转换, 而可以直接将它当作需要的类型来使用: ```KOTLIN //sampleStart fun getStringLength(obj: Any): Int? { if (obj is String) { // 在这个分支中, `obj` 的类型会被自动转换为 `String` return obj.length } // 在类型检查所影响的分支之外, `obj` 的类型仍然是 `Any` return null } //sampleEnd fun main() { fun printLength(obj: Any) { println("Getting the length of '$obj'. Result: ${getStringLength(obj) ?: "Error: The object is not a string"} ") } printLength("Incomprehensibilities") printLength(1000) printLength(listOf(Any())) } ``` 或者: ```KOTLIN //sampleStart fun getStringLength(obj: Any): Int? { if (obj !is String) return null // 在这个分支中, `obj` 的类型会被自动转换为 `String` return obj.length } //sampleEnd fun main() { fun printLength(obj: Any) { println("Getting the length of '$obj'. Result: ${getStringLength(obj) ?: "Error: The object is not a string"} ") } printLength("Incomprehensibilities") printLength(1000) printLength(listOf(Any())) } ``` 甚至还可以: ```KOTLIN //sampleStart fun getStringLength(obj: Any): Int? { // 在 `&&` 运算符的右侧, `obj` 的类型会被自动转换为 `String` if (obj is String && obj.length >= 0) { return obj.length } return null } //sampleEnd fun main() { fun printLength(obj: Any) { println("Getting the length of '$obj'. Result: ${getStringLength(obj) ?: "Error: The object is not a string"} ") } printLength("Incomprehensibilities") printLength("") printLength(1000) } ``` 参见 [类](classes.html) 和 [类型转换](typecasts.html).