Kotlin_lesson_02_流程控制

if表达式

1
2
3
4
5
6
7
8
9
10
11
// Traditional usage
var max = a
if (a < b) max = b
// With else
var max: Int if (a > b) {
max = a
} else {
max = b
}
// As expression
val max = if (a > b) a else b

if的分支可以是代码块

1
2
3
4
5
val max = if (a > b) {
print("Choose a") a
} else {
print("Choose b") b
}

如果是用if做表达式而不是表示一种状态逻辑,则必须有else的分支。

When表达式

when代替switch结构

1
2
3
4
5
6
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> { // Note the block
print("x is neither 1 nor 2") }
}

when接口会顺序匹配他的所有条件分支,并执行所有满足条件的分支。when不但能用于表达式,同时也能表示状态值。如果当作时表达式,满足条件的分支将是整个表达式的值。如果作为状态值,则条件所对应的值不会影响表达式的值,只是满足条件的最后一个分支的值为整个表达式的值。

如果有多个条件需要满足,则只需把多个条件连接写出来用逗号隔开:

1
2
3
when (x) {
0, 1 -> print("x == 0 or x == 1") else -> print("otherwise")
}

我们可以用任意的表达式作为条件而不仅仅是常数:

1
2
3
when (x) {
parseInt(s) -> print("s encodes x") else -> print("s does not encode x")
}

我们也可以去检验一个值是否存在一个范围内或者集合中通过in 或者!in

1
2
3
4
5
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")
}

另外也可用于判断一些特殊类型:

1
2
3
val hasPrefix = when(x) {
is String -> x.startsWith("prefix") else -> false
}

when也可以替换if-else if结构题,当不写参数的时候,每个条件分支为boolean表达式,分支为true的时候执行:

1
2
3
when {
x.isOdd() -> print("x is odd") x.isEven() -> print("x is even") else -> print("x is funny")
}

for循环

for循环可以迭代任何可以迭代的东西。语法如下:

1
for (item in collection) print(item)

也可以写为代码块:

1
2
3
for (item: Int in ints) {
// ...
}

如前所述,迭代器提供了三个方法:

  • iterator()生成迭代器
  • next() 游标
  • hasNext() boolean

如下对array进行遍历:

1
2
3
4
5
6
7
for (i in array.indices) {
print(array[i])
}
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}

While循环

1
2
3
4
5
6
while (x > 0) {
x--
}
do {
val y = retrieveData()
} while (y != null) // y is visible here!

Break和contunue在循环中的使用

kotlin支持循环体中传统的break和continue操作符

返回和跳过

kotlin又三种跳转结构表达式:

  • return。默认跳出最近的方法体。
  • break。跳出最近的循环
  • continue。跳过当前步骤,继续下一步循环

以上操作符可以运用在比较大的表达式中

1
val s = person.name ?: return

break和continue标签

任何表达式在kotlin中建议使用label。lable接口为lableName@.例如abc@,foobar.标记一个表达式,我们直接将标记放在表达式之前:

1
2
loop@ for (i in 1..100) { // ...
}

我们可以使用break或者continue结束某个带标签的表达式

1
2
3
4
5
loop@ for (i in 1..100) {
for (j in 1..100) {
if (...) break@loop
}
}

return某个标签表达式

1
2
3
4
5
6
fun foo() {
ints.forEach {
if (it == 0) return
print(it)
}
}

可以通过增加标签,而结束对应方法

1
2
3
4
5
6
fun foo() {
ints.forEach lit@ {
if (it == 0) return@lit
print(it)
}
}

在lambda表达式重,通常会引用内部方法名为label

1
2
3
4
5
6
fun foo() {
ints.forEach {
if (it == 0) return@forEach
print(it)
}
}

当然,也可以奖lambda表达式替换为匿名方法

1
2
3
4
5
6
fun foo() {
ints.forEach(fun(value: Int) {
if (value == 0) return
print(value)
})
}

当返回一个值时,会返回对应对象的引用值

1
return@a 1

返回的不是一个表达式,而是 标签为1的值为1.