if
kotlin 没有三元表达式。直接返回一个值。
// 传统用法
fun ifFlow(a: Int, b: Int) {
// 传统写法
var max = a
if (a < b) max = b
// else
var max2: Int
if (a > b) {
max2 = a
} else {
max2 = b
}
// 作为表达式
val max3 = if (a > b) a else b
}
复制代码
代码块的最后一行作为返回值:
fun ifBlock(a: Int, b: Int) {
// 代码块最后一行表达式的值就是 max 的值
val max = if (a > b) {
print("Choose a")
a
} else {
print("Choose b")
b
}
println("max = $max")
}
复制代码
when
when 代替了 switch 。
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> { // Note the block
print("x is neither 1 nor 2")
}
}
复制代码
可以用逗号分隔条件
when (x) {
0, 1 -> print("x == 0 or x == 1")
else -> print("otherwise")
}
复制代码
可以用任意的表达式作为判断
when (x) {
parseInt(s) -> print("s encodes x")
else -> print("s does not encode x")
}
复制代码
可以用 in 检查是否在一个区间内
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")
}
复制代码
用 is 作为条件,判断是否是 String。不需要强转类型。 判断语句返回的都是 Boolean 类型,返回值可以省略
fun hasPrefix(x:Any) = when(x){
is String -> x.startsWith("prefix")
else -> false
}
复制代码
when 可以代替 if else 语句
fun replaceIfWithWhen(x: Int) {
when {
x > 0 -> println("x > 0")
x < 0 -> println("x < 0")
else -> println("x = 0")
}
}
复制代码
for 循环
for 循环迭代器。给提供了迭代器的对象使用。类似 foreach
for (item in collection) print(item)
复制代码
没有迭代器的根据下标遍历. 类似 java 的
for(int i;i < size;i++){
}
复制代码
使用 array.indices 获得一个下标范围。在这个范围里面迭代,底层编译是优化过的,没有额外对象创建。
fun forLoopByIndex(list:Array<String>){
for (i in list.indices){
println(list[i])
}
}
复制代码
也可以使用 array.withIndex
fun forLoopByWithIndex(list:List<String>){
for ((index,value) in list.withIndex()){
println("index = $index , value = $value")
}
}
复制代码
while 循环
while 语法和 java 是一致的。
while(x>0){
x --
}
do{
val y = retrieveData()
}while(y != null)
复制代码
break continue
支持传统的 break continue