Kotlin控制流程–否则,用于循环,同时,范围
在本教程中,我们将介绍编程的一个重要方面,即Kotlin Control Flow语句。
我们将研究构成任何编程语言代码核心的if,else,range,for,for,while,whenrepeat,continue break等关键字。
让我们从IntelliJ Idea中创建一个Kotlin项目开始,与每个运算符一起开始。
Kotlin if else语句
在Kotlin中,运算符的行为方式与Java中相同。
如果条件为真,if将执行代码的特定部分。
它可以有一个可选的else子句。
以下代码来自IntelliJ项目中的Test.kt类。
fun main(args: Array<String>) {
var a = 4
var b = 5
var max = a
if (a < b)
max = b
if (a > b) {
max = a
} else {
max = b
}
println("a is $a b is $b max is $max")
}
在Kotlin中,是否还可以将其用作表达式以返回值。
a = 5
b = 4
//if else returns a value in Kotlin
max = if (a > b) a else b
print("a is $a b is $b max is $max")
这样Kotlin通过使用if else作为表达式来消除三元运算符的使用。
在另一个视图中,以if-else条件存在的最后一条语句作为值返回。
下面的示例演示了相同的内容。
max = if(a>b)
{
println("a is greater than b")
println("max is a")
a
}
else{
println("b is greater than a")
println("max is b")
b
}
println("max is $max")
//Following is printed on the log console.
a is greater than b
max is a
max is 5
Kotlin for循环
Kotlin中的for循环语法与Java中的语法不同。
For循环用于根据特定条件迭代项目列表。
以下是Kotlin中for循环的实现,以打印数字0到5。
for (i in 0..5) {
print(i)
}
下面列出了从上述语法中得出的一些推论:
Kotlin使我们免于声明
i的类型上下限(包括)在" .."运算符的两侧定义。
" in"关键字用于迭代范围。
您的另一种情况是,我们使用for-in循环遍历数组。
val items = listOf(10, 20, 30, 40)
for (i in items)
println("value is $i")
//Following is printed to the console.
value is 10
value is 20
value is 30
value is 40
为了打印元素的索引,我们在数组上调用indices方法。
val items = listOf(10, 20, 30, 40)
for (i in items.indices)
println("value is $i")
//Following is printed to the console:
value is 0
value is 1
value is 2
value is 3
为了访问迭代中元素的索引和值,使用了" withIndex()"函数。
val items = listOf(10, 20, 30, 40)
for ((i,e) in items.withIndex())
println("the index is $i and the element is $e")
//Following is printed on the console:
the index is 0 and the element is 10
the index is 1 and the element is 20
the index is 2 and the element is 30
the index is 3 and the element is 40
Kotlin forEach循环
ForEach循环为每个可迭代项重复一组语句,如下所示。
(2..5).forEach{
println(it)
}
//or
(2..5).forEach{
i -> println(i)
}
//Following is printed on the console:
2
3
4
5
它是默认的可迭代变量,用于保存当前迭代器的值。
在第二种情况下,我们将使用自定义变量。
Kotlin 范围Range
在以上各节中,我们已经看到..运算符代表一个范围。
(2..4).forEach{
println(it)
}
//Following gets printed on the console:
2
3
4
要检查某个元素是否在范围内,我们使用" in"和"!in"关键字,如下所示。
var x = 5
if(x in 1..10)
{
print("x exists in range") //this gets printed
}
else{
print("x does not exist in range")
}
x = 15
if(x !in 1..10)
{
print("x does not exist in range") //this gets printed
}
else{
print("x does exist in range")
}
并且以下应该以相同的方式工作。
对?
var x = 5
if(x in 10..1)
{
print("x exists in range")
}
else{
print("x does not exist in range") //Ironically, this gets printed.
}
for (i in 5..0)
print(i) //prints nothing
没有。
范围" .."不能以相反的顺序使用。
这是我们使用downTo关键字的地方。
下面的代码将起作用:
var x = 5
if(x in 10 downTo 1)
{
print("x exists in range") //this gets printed
}
else{
print("x does not exist in range")
}
for (i in 5 downTo 0)
print(i) //543210
为了从范围中排除最后一个元素,我们使用关键字"直到"。
for (i in 1 until 4) {
print(i)
}
//prints 123
要逐步遍历范围,我们使用关键字step。
for (i in 1..5 step 3) print(i) //prints 14 for (i in 4 downTo 1 step 2) print(i) //prints 42
Kotlin while循环
Kotlin中的while和do-while循环的行为与Java中的相同。
var i = 0
do {
i+=5
println("Value of i is $i") //prints 5
} while(i<1)
i=0
while(i<=5) {
print(i)
i++
}
//prints 012345
Kotlin break 和continue
break用于退出循环。
" continue"用于转到循环的下一个迭代。
Kotlin让我们可以在中断处贴上标签并继续执行语句,以指示触发其操作的循环,如下所示。
customLabel@ for(y in 10 downTo 5) { //applying the custom label
if(y == 6) {
print("x is $y breaking here")
break@customLabel //specifing the label
} else {
print("continue to next iteration")
continue@customLabel
}
}
Kotlin repeat和when
repeat允许我们在循环中执行N次语句(其中N是指定为参数的数目)。
以下代码段将打印该语句组3次。
repeat(3) {
println("Hello World!")
println("Kotlin Control Flow")
}
Kotlin中的when等效于其他语言中的switch,但语法不同,功能更强大!下面是" when"运算符的基本示例。
var num = 10
when (num) {
0 -> print("value is 0")
5 -> print("value is 5")
else -> {
print("value is neither 0 nor 5") //this gets printed.
}
}
when运算符将参数与所有分支匹配。
如果不匹配,则打印" else"语句。else语句类似于switch中的default。
when运算符也可以用于返回值,类似于else。
var valueLessThan100 = when(101){
in 1 until 101 -> true
else -> {
false
}
}
print(valueLessThan100) //false
更进一步,我们可以使用Any类型来检查分支,如下所示。
fun month(month: Any)
{
when(month)
{
1 -> print("January")
2-> print("February")
"MAR" -> print("March")
else -> { print("Any other month or it is invalid. when operator takes generic type Any") }
}
}
month(1) //"January"
month("MAR") //"March"
Kotlin控制流语句示例
总结我们Kotlin项目中的控制流,这就是我们Kotlin类文件的外观:
fun main(args: Array<String>) {
var a = 4
var b = 5
var max = a
if (a < b)
max = b
if (a > b) {
max = a
} else {
max = b
}
println("a is $a b is $b max is $max")
a = 5
b = 4
//if else returns a value in Kotlin
max = if (a > b) a else b
println("a is $a b is $b max is $max")
max = if(a>b)
{
println("a is greater than b")
println("max is a")
a
}
else{
println("b is greater than a")
println("max is b")
b
}
println("max is $max")
val items = listOf(10, 20, 30, 40)
for ((i,e) in items.withIndex())
println("index is $i and element is $e")
(2..5).forEach{
print(it)
}
var x = 5
if(x in 10 downTo 1)
{
print("x exists in range")
}
else{
print("x does not exist in range")
}
var i = 0
do {
i+=5
println("Value of i is $i")
} while(i<1)
i=0
while(i<=5) {
print(i)
i++
}
customLabel@ for(y in 10 downTo 5) { //appling the custom label
if(y == 6) {
print("x is $y breaking here")
break@customLabel //specifing the label
} else {
print("continue to next iteration")
continue@customLabel
}
}
repeat(3) {
println("Hello World!")
println("Kotlin Control Flow")
}
var num = 10
when (num) {
0 -> print("value is 0")
5 -> print("value is 5")
else -> {
print("value is neither 0 nor 5")
}
}
var valueLessThan100 = when(101){
in 1 until 101 -> true
else -> {
false
}
}
print(valueLessThan100) //false
month(1)
month("MAR")
}
fun month(month: Any)
{
when(month)
{
1 -> print("January")
2-> print("February")
"MAR" -> print("March")
else -> { print("Any other month or it is invalid. when operator takes generic type Any") }
}
}

