5.1.1 基础语法概览
原文链接: https://kotlinlang.org/docs/basic-syntax.html
5.1.1 基础语法概览
这里汇集了一些基础语法元素及示例。每一节的末尾都会给出指向相关主题详细说明的链接。
你也可以通过 JetBrains Academy 的免费课程 Kotlin Core track 学习 Kotlin 的全部要点。
包定义与导入
包的声明应放在源文件顶部:
1
2
3
4
5
| package my.demo
import kotlin.text.*
// ...
|
目录与包并不需要匹配:源文件可以放在文件系统中的任意位置。
参见包。
程序入口点
Kotlin 应用的入口点是 main 函数:
1
2
3
| fun main() {
println("Hello world!")
}
|
main 的另一种形式接受数量可变的 String 参数:
1
2
3
| fun main(args: Array<String>) {
println(args.contentToString())
}
|
输出到标准输出
print 把它的参数输出到标准输出:
1
2
3
4
| fun main() {
print("Hello ")
print("world!")
}
|
println 输出它的参数并换行,因此下一次输出的内容会出现在新的行上:
1
2
3
4
| fun main() {
println("Hello world!")
println(42)
}
|
readln() 函数从标准输入读取内容。它把用户输入的整行内容作为一个字符串读取。
你可以把 println()、readln() 和 print() 函数配合使用,输出请求输入的提示并显示用户输入的内容:
1
2
3
4
5
6
7
8
9
10
| // Prints a message to request input
println("Enter any word: ")
// Reads and stores the user input. For example: Happiness
val yourWord = readln()
// Prints a message with the input
print("You entered the word: ")
print(yourWord)
// You entered the word: Happiness
|
更多信息请参阅读取标准输入。
函数
一个接收两个 Int 参数、返回 Int 的函数:
1
2
3
4
5
6
7
8
| fun sum(a: Int, b: Int): Int {
return a + b
}
fun main() {
print("sum of 3 and 5 is ")
println(sum(3, 5))
}
|
函数体可以是一个表达式。它的返回类型会被推断出来:
1
2
3
4
5
| fun sum(a: Int, b: Int) = a + b
fun main() {
println("sum of 19 and 23 is ${sum(19, 23)}")
}
|
一个不返回有意义值的函数:
1
2
3
4
5
6
7
| fun printSum(a: Int, b: Int): Unit {
println("sum of $a and $b is ${a + b}")
}
fun main() {
printSum(-1, 8)
}
|
Unit 返回类型可以省略:
1
2
3
4
5
6
7
| fun printSum(a: Int, b: Int) {
println("sum of $a and $b is ${a + b}")
}
fun main() {
printSum(-1, 8)
}
|
参见函数。
变量
在 Kotlin 中,声明变量以关键字 val 或 var 开头,后面跟上变量名。
使用 val 关键字声明的变量只能被赋值一次。这类变量是不可变、只读的局部变量,初始化之后不能再赋予其他值:
1
2
3
4
5
6
| fun main() {
// Declares the variable x and initializes it with the value of 5
val x: Int = 5
// 5
println(x)
}
|
使用 var 关键字声明的变量可以重新赋值。这类变量是可变的,你可以在初始化之后修改它们的值:
1
2
3
4
5
6
7
8
| fun main() {
// Declares the variable x and initializes it with the value of 5
var x: Int = 5
// Reassigns a new value of 6 to the variable x
x += 1
// 6
println(x)
}
|
Kotlin 支持类型推断,会自动识别所声明变量的数据类型。声明变量时可以省略变量名后面的类型:
1
2
3
4
5
6
| fun main() {
// Declares the variable x with the value of 5;`Int` type is inferred
val x = 5
// 5
println(x)
}
|
变量只能在初始化之后使用。你既可以在声明时就初始化变量,也可以先声明、之后再初始化。在后一种情况下,必须指定数据类型:
1
2
3
4
5
6
7
8
9
10
11
12
| fun main() {
// Initializes the variable x at the moment of declaration; type is not required
val x = 5
// Declares the variable c without initialization; type is required
val c: Int
// Initializes the variable c after declaration
c = 3
// 5
// 3
println(x)
println(c)
}
|
你可以在顶层声明变量:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| val PI = 3.14
var x = 0
fun incrementX() {
x += 1
}
// x = 0; PI = 3.14
// incrementX()
// x = 1; PI = 3.14
fun main() {
println("x = $x; PI = $PI")
incrementX()
println("incrementX()")
println("x = $x; PI = $PI")
}
|
关于声明属性的信息,请参阅属性。
创建类与实例
要定义类,请使用 class 关键字:
类的属性可以列在类声明中,也可以写在类体中:
1
2
3
| class Rectangle(val height: Double, val length: Double) {
val perimeter = (height + length) * 2
}
|
类声明中列出的参数会自动提供对应的默认构造器:
1
2
3
4
5
6
7
| 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:
1
2
3
4
5
| open class Shape
class Rectangle(val height: Double, val length: Double): Shape() {
val perimeter = (height + length) * 2
}
|
关于构造器和继承的更多信息,请参阅类和对象与实例。
与大多数现代语言一样,Kotlin 支持单行(或行尾)注释和多行(块)注释:
1
2
3
4
| // This is an end-of-line comment
/* This is a block comment
on multiple lines. */
|
Kotlin 中的块注释可以嵌套:
1
2
3
| /* The comment starts here
/* contains a nested comment */
and ends here. */
|
关于文档注释语法的信息,请参阅为 Kotlin 代码编写文档。
字符串模板
1
2
3
4
5
6
7
8
9
10
| fun main() {
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)
}
|
详情请参阅字符串模板。
条件表达式
1
2
3
4
5
6
7
8
9
10
11
| fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}
fun main() {
println("max of 0 and 42 is ${maxOf(0, 42)}")
}
|
在 Kotlin 中,if 也可以用作表达式:
1
2
3
4
5
| fun maxOf(a: Int, b: Int) = if (a > b) a else b
fun main() {
println("max of 0 and 42 is ${maxOf(0, 42)}")
}
|
参见 if 表达式。
for 循环
1
2
3
4
5
6
| fun main() {
val items = listOf("apple", "banana", "kiwifruit")
for (item in items) {
println(item)
}
}
|
或者:
1
2
3
4
5
6
| fun main() {
val items = listOf("apple", "banana", "kiwifruit")
for (index in items.indices) {
println("item at $index is ${items[index]}")
}
}
|
参见 for 循环。
while 循环
1
2
3
4
5
6
7
8
| fun main() {
val items = listOf("apple", "banana", "kiwifruit")
var index = 0
while (index < items.size) {
println("item at $index is ${items[index]}")
index++
}
}
|
参见 while 循环。
when 表达式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| fun describe(obj: Any): String =
when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}
fun main() {
println(describe(1))
println(describe("Hello"))
println(describe(1000L))
println(describe(2))
println(describe("other"))
}
|
参见 when 表达式与语句。
区间
用 in 运算符检查某个数字是否在区间内:
1
2
3
4
5
6
7
| fun main() {
val x = 10
val y = 9
if (x in 1..y+1) {
println("fits in range")
}
}
|
检查某个数字是否在区间之外:
1
2
3
4
5
6
7
8
9
10
| fun main() {
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
2
3
4
5
| fun main() {
for (x in 1..5) {
print(x)
}
}
|
或者遍历一个步进序列:
1
2
3
4
5
6
7
8
9
| fun main() {
for (x in 1..10 step 2) {
print(x)
}
println()
for (x in 9 downTo 0 step 3) {
print(x)
}
}
|
参见区间与步进序列。
集合
遍历一个集合:
1
2
3
4
5
6
| fun main() {
val items = listOf("apple", "banana", "kiwifruit")
for (item in items) {
println(item)
}
}
|
用 in 运算符检查集合是否包含某个对象:
1
2
3
4
5
6
7
| fun main() {
val items = setOf("apple", "banana", "kiwifruit")
when {
"orange" in items -> println("juicy")
"apple" in items -> println("apple is fine too")
}
}
|
使用 lambda 表达式过滤和映射集合:
1
2
3
4
5
6
7
8
| fun main() {
val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
fruits
.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.uppercase() }
.forEach { println(it) }
}
|
参见集合概览。
可空值与空值检查
当某个引用可能为 null 时,必须显式地把它标记为可空。可空类型的名称以 ? 结尾,例如 Int?。
如果 str 不是整数,则返回 null:
1
2
3
| fun parseInt(str: String): Int? {
return str.toIntOrNull()
}
|
使用返回可空值的函数:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| 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("'$arg1' or '$arg2' is not a number")
}
}
fun main() {
printProduct("6", "7")
printProduct("a", "7")
printProduct("a", "b")
}
|
或者:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
| 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() {
printProduct("6", "7")
printProduct("a", "7")
printProduct("99", "b")
}
|
参见空安全。
类型检查与自动转换
is 运算符检查某个表达式是否为某个类型的实例。如果对不可变的局部变量或属性做了特定类型的检查,就不必再显式转换:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| 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() {
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()))
}
|
或者:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| 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() {
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()))
}
|
甚至还可以这样:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| 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() {
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)
}
|
参见类和类型转换。