[置顶] Kotlin简明学习—流程控制

时间:2022-02-10 20:09:00

每个语言应该说都是有流程控制的,流程控制是实现逻辑的关键。在Java中我们熟悉都流程控制有if else,switch,for循环。在Kotlin中对应的是if else,when,for循环。Kotlin的流程控制跟Java的有所不同,可以把if else流程控制看做是表达式,对变量可以进行赋值操作。

if else

1.跟Java中的if else完全一样,就是分支选择

val age = 15

if (age <= 12) {
println("Child")
} else if (age >= 13 && age <= 17) {
println("Teenager")
} else {
println("Adult")
}

输出

Teenager

2.不同于Java,可以赋值

val age = 20
val personType = if (age <= 12) {
"Child"
} else if (age >= 13 && age <= 17) {
"Teenager"
} else {
"Adult"
}

println(personType)

输出

Teenager

when

1.when相当于Java中swich

val num = 77

when (num) {
in 1..10 -> println("Number is in the range")
!in 10..20 -> println("Number is outside the range")
else -> println("None of the above")
}

输出:

Number is outside the range

2.赋值用法

val x = "Batman"

// If "when" is used as an expression then it MUST be exhaustive.
val hasPrefix = when (x) {
is String -> x.startsWith("Bat")
else -> false
}
hasPrefix

for循环


val days = listOf("Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun")
for (d in days) { println(d) }
for (x in 1..10) { println(x) }

val nzPop = mapOf("AUCK" to 1500000, "WLG" to 405000, "CHCH" to 500000, "GIS" to 36100)
for ((key, value) in nzPop) {
println("$key -> $value")
}

while和do while

var x = 1
while (x <= 10) {
println(x)
++x
}

var x = 12
do {
println(x)
++x
} while (x <= 10)

参考文献

https://medium.com/@napperley/kotlin-tutorial-6-control-flow-340cbffc18b5

Kotlin简明学习—文章列表