funprintSum(a: Int, b: Int): Unit { println("sum of $a and $b is ${a + b}") }
Unit可以被省略。
1 2 3
funprintSum(a: Int, b: Int) { println("sum of $a and $b is ${a + b}") }
定义变量(Variables)
只读变量:
1 2 3 4
val a: Int = 1// 定义变量时复制 val b = 2// 类型推断:`Int` val c: Int// 没有立即赋值需要显式指定变量类型 c = 3// deferred assignment
可变变量:
1 2
var x = 5 // `Int` type is inferred x += 1
注释(Comments)
kotlin的注释可以嵌套
1 2 3 4
// 单行注释
/* 块注释, 可以包含多行 */
字符串模板(string templates)
1 2 3 4 5 6 7 8
var a = 1 // 简单变量模板: val s1 = "a is $a"
a = 2
// 模板中包含表达式 val s2 = "${s1.replace("is", "was")}, but now is $a"
条件表达式(conditional expressions)
1 2 3 4 5 6 7
funmaxOf(a: Int, b: Int): Int { if (a > b) { return a } else { return b } }
1
fun maxOf(a: Int, b: Int) = if (a > b) aelse b
检查null
如果函数返回null,必须显式在返回值类型后面加上?
1 2 3
funparseInt(str: String): Int? { // ... }
1 2 3 4 5 6 7 8 9 10 11 12 13
funprintProduct(arg1: String, arg2: String) { val x = parseInt(arg1) val y = parseInt(arg2)
// 直接计算 `x * y` 会产生编译错误,因为x和y可能是null if (x != null && y != null) { // x 和 y 检查null之后会自动转型成非空类型(non-nullable) println(x * y) } else { println("either '$arg1' or '$arg2' is not a number") } }
val x = 10 val y = 9 if (x in1..y+1) { println("fits in range") }
1 2 3 4 5 6 7 8
vallist = listOf("a", "b", "c")
if (-1 !in0..list.lastIndex) { println("-1 is out of range") } if (list.size !inlist.indices) { println("list size is out of valid list indices range too") }
迭代
1 2 3
for (x in1..5) { print(x) }
设置迭代步长
for (x in 1..10 step 2) { print(x) } println() for (x in 9 downTo 0 step 3) { print(x) }
使用集合类
迭代
1 2 3
for (iteminitems) { println(item) }
判断元素是否存在于集合中
1 2 3 4
when { "orange"in items -> println("juicy") "apple"in items -> println("apple is fine too") }