原文

基本语法

包定义

在源文件的开头定义包:

1. package my.demo
2. import java.util.*
3. //...

包名不必和文件夹路径一致:源文件可以放在任意位置。

更多请参看 包(package)

定义函数

定义一个函数接受两个 int 型参数,返回值为 int :

1. fun sum(a: Int, b: Int): Int {
2. return a + b
3. }

只有一个表达式作为函数体,以及自推导型的返回值:

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

返回一个没有意义的值:

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

Unit 的返回类型可以省略:

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

更多请参看函数

定义局部变量

一次赋值(只读)的局部变量:

1. val a: Int = 1  // 立刻赋值
2. val b = 2   // `Int` 类型是自推导的
3. val c: Int  // 没有初始化器时要指定类型
4. c = 3       // 推导型赋值

可修改的变量:

1. var x = 5 // `Int` type is inferred
2. x += 1

更多请参看属性和字段

注释

与 java 和 javaScript 一样,Kotlin 支持单行注释和块注释。

1. // 单行注释

3. /*  哈哈哈哈
4. 这是块注释 */

与 java 不同的是 Kotlin 的 块注释可以级联。

参看文档化 Kotlin 代码学习更多关于文档化注释的语法。

使用字符串模板

1. var a = 1
2. // simple name in template:
3. val s1 = "a is $a"

5. a = 2
6. // arbitrary expression in template:
7. val s2 = "${s1.replace("is", "was")}, but now is $a"

更多请参看字符串模板

使用条件表达式

1. fun maxOf(a: Int, b: Int): Int {
2. if (a > b) {
3. return a
4. } else {
5. return b
6. }
7. }

使用 if 作为表达式:

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

更多请参看 if 表达式

使用可空变量以及空值检查

当空值可能出现时应该明确指出该引用可空。

当 str 中不包含整数时返回空:

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

使用一个返回可空值的函数:

1. fun parseInt(str: String): Int? {
2. return str.toIntOrNull()
3. }

5. fun printProduct(arg1: String, arg2: String) {
6. val x = parseInt(arg1)
7. val y = parseInt(arg2)

9. // 直接使用 x*y 会产生错误因为它们中有可能会有空值
10. if (x != null && y != null) {
11. // x 和 y 将会在空值检测后自动转换为非空值
12. println(x * y)
13. }
14. else {
15. println("either '$arg1' or '$arg2' is not a number")
16. }
17. }

或者这样

1. if (x == null) {
2. println("Wrong number format in arg1: '${arg1}'")
3. return
4. }
5. if (y == null) {
6. println("Wrong number format in arg2: '${arg2}'")
7. return
8. }

10. // x and y are automatically cast to non-nullable after null check
11. println(x * y)

更多请参看空安全

使用值检查以及自动转换

使用 is 操作符检查一个表达式是否是某个类型的实例。如果对不可变的局部变量或属性进行过了类型检查,就没有必要明确转换:

1. fun getStringLength(obj: Any): Int? {
2. if (obj is String) {
3. // obj 将会在这个分支中自动转换为 String 类型
4. return obj.length
5. }

7. // obj 在类型检查分支外仍然是 Any 类型
8. return null
9. }

或者这样

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

4. // obj 将会在这个分支中自动转换为 String 类型
5. return obj.length
6. }

甚至可以这样

1. fun getStringLength(obj: Any): Int? {
2. // obj 将会在&&右边自动转换为 String 类型
3. if (obj is String && obj.length > 0) {
4. return obj.length
5. }

7. return null
8. }

更多请参看 类 和 类型转换

使用 for 循环

1. val items = listOf("apple", "banana", "kiwi")
2. for (item in items) {
3. println(item)
4. }

或者

1. val items = listOf("apple", "banana", "kiwi")
2. for (index in items.indices) {
3. println("item at $index is ${items[index]}")
4. }

参看for循环

使用 while 循环

1. val items = listOf("apple", "banana", "kiwi")
2. var index = 0
3. while (index < items.size) {
4. println("item at $index is ${items[index]}")
5. index++
6. }

参看while循环

使用 when 表达式

1. fun describe(obj: Any): String =
2. when (obj) {
3. 1          -> "One"
4. "Hello"    -> "Greeting"
5. is Long    -> "Long"
6. !is String -> "Not a string"
7. else       -> "Unknown"
8. }

参看when表达式

使用ranges

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

1. val x = 10
2. val y = 9
3. if (x in 1..y+1) {
4. println("fits in range")
5. }

检查数值是否在范围外:

1. val list = listOf("a", "b", "c")

3. if (-1 !in 0..list.lastIndex) {
4. println("-1 is out of range")
5. }
6. if (list.size !in list.indices) {
7. println("list size is out of valid list indices range too")
8. }

使用范围内迭代:

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

或者使用步进:

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

参看Ranges

使用集合

对一个集合进行迭代:

1. for (item in items) {
2. println(item)
3. }

使用 in 操作符检查集合中是否包含某个对象

1. when {
2. "orange" in items -> println("juicy")
3. "apple" in items -> println("apple is fine too")
4. }

使用lambda表达式过滤和映射集合:

1. fruits
2. .filter { it.startsWith("a") }
3. .sortedBy { it }
4. .map { it.toUpperCase() }
5. .forEach { println(it) }

参看高阶函数和lambda表达式