原文

基本语法

包定义和引入

在源文件的开头定义包:

  1. package my.demo
  2. import kotlin.text.*
  3. // ...

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

更多请参看 包(package)

程序入口

Kotlin 应用的入口是 main 函数.

  1. fun main() {
  2. println("Hello world!")
  3. }

函数

下面的函数接受两个 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. }

更多请参看函数

变量

只读的本地变量通过val关键字定义.该类变量只能赋值一次:

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

被关键字var修饰的变量可以重新赋值:

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

顶级变量:

  1. val PI = 3.14
  2. var x = 0
  3. fun incrementX() {
  4. x += 1
  5. }

更多请参看属性和字段

注释

与多数现代语言一样,Kotlin 支持单行注释(行尾注释)和多行注释(块注释)。

  1. // 行尾注释
  2. /* 这是块注释
  3. 可以在多行注释 */

Kotlin 块注释可以嵌套.

  1. /* The comment starts here
  2. /* contains a nested comment */
  3. and ends here. */

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

字符串模板

  1. var a = 1
  2. // simple name in template:
  3. val s1 = "a is $a"
  4. a = 2
  5. // arbitrary expression in template:
  6. 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. }

kotin 中可以使用 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 printProduct(arg1: String, arg2: String) {
  2. val x = parseInt(arg1)
  3. val y = parseInt(arg2)
  4. // Using `x * y` yields error because they may hold nulls.
  5. if (x != null && y != null) {
  6. // x and y are automatically cast to non-nullable after null check
  7. println(x * y)
  8. }
  9. else {
  10. println("'$arg1' or '$arg2' is not a number")
  11. }
  12. }

或者

  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. }
  9. // x and y are automatically cast to non-nullable after null check
  10. println(x * y)

更多请参看空安全

类型检查以及自动转换

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

  1. fun getStringLength(obj: Any): Int? {
  2. if (obj is String) {
  3. // obj 将会在这个分支中自动转换为 `String` 类型
  4. return obj.length
  5. }
  6. // obj 在类型检查分支外仍然是 Any 类型
  7. return null
  8. }

或者

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

甚至可以这样

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

更多请参看 类型转换

for 循环

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

或者

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

参看for循环

while 循环

  1. val items = listOf("apple", "banana", "kiwifruit")
  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")
  2. if (-1 !in 0..list.lastIndex) {
  3. println("-1 is out of range")
  4. }
  5. if (list.size !in list.indices) {
  6. println("list size is out of valid list indices range, too")
  7. }

参看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. val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
  2. fruits
  3. .filter { it.startsWith("a") }
  4. .sortedBy { it }
  5. .map { it.toUpperCase() }
  6. .forEach { println(it) }

参看集合概述

创建基本类以及实例:

  1. val rectangle = Rectangle(5.0, 2.0)
  2. val triangle = Triangle(3.0, 4.0, 5.0)

参看对象及实例