条件与循环
If 表达式
在 Kotlin 中,if
是一个表达式:它会返回一个值。 因此就不需要三元运算符(条件 ? 然后 : 否则
)。
fun main() {
val a = 2
val b = 3
var max = a
if (a < b) max = b
if (a > b) {
max = a
} else {
max = b
}
// 作为表达式
max = if (a > b) a else b
// You can also use `else if` in expressions:
val maxLimit = 1
val maxOrLimit = if (maxLimit > a) maxLimit else if (a > b) a else b
println("max is $max")
println("maxOrLimit is $maxOrLimit")
}
if
表达式的分支可以是代码块,这种情况最后的表达式作为该块的值:
val max = if (a > b) {
print("Choose a")
a
} else {
print("Choose b")
b
}
When 表达式
when
将它的参数与所有的分支条件顺序比较,直到某个分支满足条件
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
//分支条件可以为多个组合在一起
1, 2 -> print("x == 1 or x == 2")
//分支条件可以为表达式
//s.toInt() -> print("s encodes x")
//分支条件还可以为检测一个值在或者不在一个区间或者集合中
in 1..10 -> print("x is in the range")//(1..10)可以替换为一个集合
//分支条件可以检测是否为某种特定类型的值
is Int ->print("x is Int")
else -> {//都不满足
print("x is neither 1 nor 2")
}
}
when
既可以作为表达式使用也可以作为语句使用。 如果它被当做表达式, 第一个符合条件的分支的值就是整个表达式的值,如果当做语句使用, 则忽略个别分支的值。
如果其他分支都不满足条件将会求值else 分支。 如果作为一个表达式使用,那么必须有else 分支, 除非编译器能够检测出所有的可能情况都已经覆盖了。
enum class Bit {
ZERO, ONE
}
val numericValue = when (getRandomBit()) {
Bit.ZERO -> 0
Bit.ONE -> 1
// 'else' is not required because all cases are covered
}
For 循环
for循环可以遍历一个集合中的对象。
for (item in collection) print(item)
循环体可以是一个代码块。
如需在数字区间上迭代,请使用区间表达式:
fun main() {
for (i in 1..3) {
println(i)
}
for (i in 6 downTo 0 step 2) {//遍历区间6-0,每隔2遍历一次
println(i)
}
}
对区间或者数组的 循环会被编译为并不创建迭代器的基于索引的循环。
如果你想要通过索引遍历一个数组或者一个 list,你可以这么做:
fun main() {
val array = arrayOf("a", "b", "c")
for (i in array.indices) {//indices:索引范围
println(array[i])
}
/*还可以使用库函数:withIdex
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
*/
}
while 循环
while 和 do-while当循环条件满足时会持续执行它们的主体。 它们之间的区别在于条件检查的时间:
while
先检查条件,如果满足,则执行主体,然后再返回到条件检查。do-while
先执行主体,然后检查条件。 如果满足,则循环重复。 所以 的主体至少执行一次,不管条件如何。
while (x > 0) {
x--
}
do {
val y = retrieveData()
} while (y != null) // y 在此处可见
返回与跳转
Kotlin 有三种结构化跳转表达式:
return
默认从最直接包围它的函数或者匿名函数返回。break
终止最直接包围它的循环。continue
继续下一次最直接包围它的循环。
所有这些表达式都可以用作更大表达式的一部分:
val s = person.name ?: return
Break 与 Continue 标签
loop@…break@loop指定代码运行到@loop之后停止
fun main() {
loop@ for (i in 1..100) {
if(i==80) {
break@loop//遍历执行到80时停止
}
println("i is $i")
}
}
loop@…continue@loop指定代码跳过满足条件的那次循环
fun main() {
loop@ for (i in 1..100) {
if(i/80==0) {
continue@loop//从80开始遍历
}
println("i is $i")
}
}
如果与return搭配,则直接返回给lamba表达式的调用者并继续下次循环
//sampleStart
fun foo() {
listOf(1, 2, 3, 4, 5).forEach lit@{
if (it == 3) return@lit // 局部返回到该 lambda 表达式的调用者——forEach 循环
print(it)
}
print(" done with explicit label")
}
fun main() {
foo()
}
也可直接使用隐式标签
fun foo() {
listOf(1, 2, 3, 4, 5).forEach {
if (it == 3) return@forEach // 局部返回到该 lambda 表达式的调用者——forEach 循环
print(it)
}
print(" done with implicit label")
}
fun main() {
foo()
}
异常
异常类
Kotlin 中所有异常类继承自 Throwable
类。
使用 throw
表达式来抛出异常:
fun main() {
//sampleStart
throw Exception("Hi There!")
//sampleEnd
}
使用 try
……catch
表达式来捕获异常:
try {
// 一些代码
} catch (e: SomeException) {
// 处理程序
} finally {
// 可选的 finally 块
}
可以有零到多个 catch
块,finally
块可以省略。 但是 catch
与 finally
块至少需有一个。
Try 是一个表达式
这意味着它可以有一个返回值,这个返回值是try
块中最后一个表达式或者是catch
块中的最后一个表达式。
finally
块中的内容不会影响表达式的结果。
val a: Int? = try { input.toInt() } catch (e: NumberFormatException) { null }
受检异常
Kotlin 没有受检异常。
参考koltin中文文档,链接:https://book.kotlincn.net/