funmain() { //sampleStart val a: Int = 1// 立即赋值 val b = 2// 自动推断出 `Int` 类型 val c: Int// 如果没有初始值类型不能省略 c = 3// 明确赋值 //sampleEnd println("a = $a, b = $b, c = $c") }
可重新赋值的变量使用 var 关键字:
1 2 3 4 5 6 7
funmain() { //sampleStart var x = 5// 自动推断出 `Int` 类型 x += 1 //sampleEnd println("x = $x") }
顶层变量:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
//sampleStart val PI = 3.14 var x = 0
funincrementX() { x += 1 } //sampleEnd
funmain() { println("x = $x; PI = $PI") incrementX() println("incrementX()") println("x = $x; PI = $PI") }
funmain() { //sampleStart var a = 1 // 模板中的简单名称: val s1 = "a is $a" a = 2 // 模板中的任意表达式: val s2 = "${s1.replace("is", "was")}, but now is $a" //sampleEnd println(s2) }
funprintProduct(arg1: String, arg2: String) { val x = parseInt(arg1) val y = parseInt(arg2) //sampleStart // …… if (x == null) { println("Wrong number format in arg1: '$arg1'") return } if (y == null) { println("Wrong number format in arg2: '$arg2'") return }
// 在空检测后,x 与 y 会自动转换为非空值 println(x * y) //sampleEnd }
funmain() { funprintLength(obj: Any) { println("'$obj' string length is ${getStringLength(obj) ?: "... err, is empty or not a string at all"} ") } printLength("Incomprehensibilities") printLength("") printLength(1000) }
funmain() { //sampleStart val items = listOf("apple", "banana", "kiwifruit") for (item in items) { println(item) } //sampleEnd }
或者
1 2 3 4 5 6 7 8
funmain() { //sampleStart val items = listOf("apple", "banana", "kiwifruit") for (index in items.indices) { println("item at $index is ${items[index]}") } //sampleEnd }
funmain() { //sampleStart val items = listOf("apple", "banana", "kiwifruit") var index = 0 while (index < items.size) { println("item at $index is ${items[index]}") index++ } //sampleEnd }
funmain() { //sampleStart val x = 10 val y = 9 if (x in1..y+1) { println("fits in range") } //sampleEnd }
检测某个数字是否在指定区间外:
1 2 3 4 5 6 7 8 9 10 11 12
funmain() { //sampleStart val list = listOf("a", "b", "c") if (-1 !in0..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") } //sampleEnd }
funmain() { //sampleStart val rectangle = Rectangle(5.0, 2.0) // 不需要“new”关键字 val triangle = Triangle(3.0, 4.0, 5.0) //sampleEnd println("Area of rectangle is ${rectangle.calculateArea()}, its perimeter is ${rectangle.perimeter}") println("Area of triangle is ${triangle.calculateArea()}, its perimeter is ${triangle.perimeter}") }