定义包的规范应位于源文件的顶部:
package com.web3 import java.util.* // ...
不需要匹配目录和包:源文件可以任意放在文件系统中。
具有返回Int
类型的两个Int
参数的函数:
fun sum(a: Int, b: Int): Int { return a + b } fun main(args: Array<String>) { print("sum of 3 and 5 is ") println(sum(3, 5)) }函数与表达主体和推断返回值的类型:
fun sum(a: Int, b: Int) = a + b fun main(args: Array<String>) { 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<String>) { printSum(-1, 8) }
Unit
返回类型可以省略:
fun printSum(a: Int, b: Int) { println("sum of $a and $b is ${a + b}") } fun main(args: Array<String>) { printSum(-1, 8) }
分配一次(只读)局部变量:
fun main(args: Array<String>) { 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") }
可变变量:
fun main(args: Array<String>) { var x = 5 // `Int` type is inferred x += 1 println("x = $x") }
Kotlin中的注释类似于Java和JavaScript,Kotlin支持行尾和块注释。
// This is an end-of-line comment /* This is a block comment on multiple lines. */
与Java不同的是,Kotlin中的块注释可以嵌套。
fun main(args: Array<String>) { 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) }
fun maxOf(a: Int, b: Int): Int { if (a > b) { return a } else { return b } } fun main(args: Array<String>) { 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<String>) { println("max of 0 and 42 is ${maxOf(0, 42)}") }
当可能为null
值时,引用必须被明确地标记为可空(null
)。
如果str
不包含整数,则返回null
:
fun parseInt(str: String): Int? { // ... }使用可返回
null
值的函数:
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<String>) { 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<String>) { printProduct("6", "7") printProduct("a", "7") printProduct("99", "b") }
is
运算符检查表达式是否是类型的实例。 如果一个不可变的局部变量或属性是指定类型,则不需要显式转换:
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<String>) { 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<String>) { 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<String>) { 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) }
fun main(args: Array<String>) { val items = listOf("apple", "banana", "kiwi") for (item in items) { println(item) } }上面代码,可以编写成如下 -
fun main(args: Array<String>) { val items = listOf("apple", "banana", "kiwi") for (index in items.indices) { println("item at $index is ${items[index]}") } }
fun main(args: Array<String>) { val items = listOf("apple", "banana", "kiwi") var index = 0 while (index < items.size) { println("item at $index is ${items[index]}") index++ } }
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<String>) { println(describe(1)) println(describe("Hello")) println(describe(1000L)) println(describe(2)) println(describe("other")) }
使用in
操作符检查数字是否在指定范围内:
fun main(args: Array<String>) { val x = 10 val y = 9 if (x in 1..y+1) { println("fits in range") } }检查一个数字是否超出指定范围:
fun main(args: Array<String>) { 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 is out of range list size is out of valid list indices range too迭代范围:
fun main(args: Array<String>) { for (x in 1..5) { print(x) } }或过程:
fun main(args: Array<String>) { for (x in 1..10 step 2) { println(x) } println("===============================") for (x in 9 downTo 0 step 3) { println(x) } }上面代码,执行结果如下 -
1 3 5 7 9 =============================== 9 6 3 0
迭代集合:
fun main(args: Array<String>) { val items = listOf("apple", "banana", "kiwi") for (item in items) { println(item) } }检查集合是否包含一个对象,使用
in
运算符:
fun main(args: Array<String>) { val items = setOf("apple", "banana", "kiwi") when { "orange" in items -> println("juicy") "apple" in items -> println("apple is fine too") } }使用
lambda
表达式过滤映射集合:
fun main(args: Array<String>) { val fruits = listOf("banana", "avocado", "apple", "kiwi") fruits .filter { it.startsWith("a") } .sortedBy { it } .map { it.toUpperCase() } .forEach { println(it) } }