Android Kotlin 开发心得笔记(2)

if...else 正常使用,不过移除了switch用更强大的when替代,when子式可以是各种返回Boolean的表达式

val x = 7 when (x) { in 1..10 -> print("x is in the range") in validNumbers -> print("x is valid") !in 10..20 -> print("x is outside the range") else -> print("none of the above") } 循环

while 和 do...while 同Java并无区别,for则有很大改变并多出了几个变种

val list = ArrayList<String>() //递增for (int i = 0; i < list.size(); i++) for (i in list.indices) { print(list[i]) } //递增for (int i = 2; i < list.size(); i++) for (i in 2..list.size-1) { print(list[i]) } //递减for (int i = list.size(); i >= 0; i--) for (i in list.size downTo 0) { print(list[i]) } //操作列表内的对象 for (item in list) { print(item) } //加强版 for((i, item) in list.witnIndex()) { print(list[i]) print(item) } //变种版 list.forEach { print(it) } list.forEach { print(it) } list.forEachIndexed { i, s -> print(list[i]) print(s) } list.forEachIndexed(object :(Int,String) -> Unit{ override fun invoke(i: Int, s: String) { print(list[i]) print(s) } })

本文永久更新链接地址

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/44130f4f0e49a77a6ac0034f98c62ddf.html