fun getStringLength(obj: Any): Int? { if (obj is String) { // `obj` 在该条件分支内自动转换成 `String` return obj.length } // 在离开类型检测分支后,`obj` 仍然是 `Any` 类型 return null }
fun main() { fun printLength(obj: Any) { println("'$obj' string length is ${getStringLength(obj) ?: "... err, not a string"} ") } printLength("Incomprehensibilities") printLength(1000) printLength(listOf(Any())) }
'Incomprehensibilities' string length is 21 '1000' string length is ... err, not a string '[java.lang.Object@3af49f1c]' string length is ... err, not a string
for 循环
1 2 3 4 5
val items = listOf("apple", "banana", "kiwifruit") for (item in items) println(item) //或者 val items2 = listOf("apple", "banana", "kiwifruit") for (index in items.indices) println("item at $index is ${items2[index]}")
while 循环
1 2 3 4 5 6 7 8 9 10
val items = listOf("apple", "banana", "kiwifruit") var index = 0 while (index < items.size) { println("item at $index is ${items[index]}") index++ }
item at 0 is apple item at 1 is banana item at 2 is kiwifruit
fun describe(obj: Any): String = when (obj) { 1 -> "One" "Hello" -> "Greeting" is Long -> "Long" !is String -> "Not a string" else -> "Unknown" }
fun main() { println(describe(1)) println(describe("Hello")) println(describe(1000L)) println(describe(2)) println(describe("other")) }
//输出 One Greeting Long Not a string Unknown
使用区间
使用 in 运算符来检测某个数字是否在指定区间内
1 2 3 4 5 6 7 8 9
fun main() { val x = 10 val y = 9 if (x in 1..y+1) { println("fits in range") } } //x 在 1 - 10 的区间 //输出 fits in range
区间迭代:
1 2 3 4
for (x in 1..5) { print(x) } // 12345
数列迭代
1 2 3 4 5 6 7 8 9
for (x in 1..10 step 2) { print(x) } println() for (x in 9 downTo 0 step 3) { print(x) } 13579 9630
Collections
对集合迭代
1 2 3 4 5 6 7 8 9 10
fun main() { val items = listOf("apple", "banana", "kiwifruit") for (item in items) { println(item) } }
apple banana kiwifruit
使用 in 运算符判断集合内是否包含某实例
1 2 3 4 5 6 7 8
fun main() { val items = setOf("apple", "banana", "kiwifruit") when { "orange" in items -> println("juicy") "apple" in items -> println("apple is fine too") } } apple is fine too
使用 lambda 表达式过滤 (filter) 与映射 (map) 集合
1 2 3 4 5 6 7 8 9 10
fun lambda() { val fruits = listOf("banana", "avocado", "apple", "kiwifruit") fruits .filter { it.startsWith("a") } //a开头 .sortedBy { it } //倒序 .map { it.toUpperCase() } //大写 .forEach { println(it) } //输出 } APPLE AVOCADO