kotlin 循环_Kotlin控制流–否则,用于循环,同时,范围
kotlin 循环
In this tutorial, we’ll be covering an important aspect of programming, namely Kotlin Control Flow statements.
We’ll look into the if else, range, for, while, when repeat, continue break keywords that form the core of any programming language code.
在本教程中,我们将介绍编程的一个重要方面,即Kotlin Control Flow语句。
我们会调查的if else , range , for , while , when repeat , continue break形成的任何编程语言代码的核心关键词。
Let’s get started with each of these operators by creating a Kotlin project in our IntelliJ Idea.
通过在IntelliJ Idea中创建一个Kotlin项目,让我们开始与每个操作员一起开始。
Kotlin (Kotlin if else)
In Kotlin, if else operators behave the same way as it does in Java.
if executes a certain section of code if the condition is true. It can have an optional else clause.
Following code is from the Test.kt class in our IntelliJ Project.
在Kotlin中,运算符的行为方式与Java中相同。
if条件为真, 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")
}
In Kotlin, if else can be used as expressions too in order to return a value.
在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")
This way Kotlin eliminates the use of ternary operator by using if else as expressions.
这样Kotlin通过使用if else作为表达式来消除三元运算符的使用。
In another view, the last statement present in an if-else condition is returned as the value.
The below example demonstrates the same.
在另一个视图中,以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 loop)
The syntax of for loop in Kotlin is different from the one in Java.
For loop is used to iterate over a list of items based on certain conditions.
Following is the implementation of for loops in Kotlin to print numbers 0 to 5.
Kotlin中的for循环语法与Java中的语法不同。
For循环用于根据特定条件遍历项目列表。
以下是Kotlin中for循环的实现,以打印数字0到5。
for (i in 0..5) {
print(i)
}
Few inferences from the above syntax are listed below:
下面列出了从上述语法中得出的少量推论:
- Kotlin saves us from declaring the type of
iKotlin使我们免于声明i的类型 - The lower and upper (including) limits are be defined on either side of
..operator. 上下限(包括)在..运算符的两侧定义。 inkeyword is used to iterate over the range.in关键字用于迭代范围。
Another case for you, where we iterate over an array using for-in loop.
您的另一种情况是,我们使用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
To print the index of the elements, we invoke the indices method on the arrays.
要打印元素的索引,我们在数组上调用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
To access the index and value of the element in the iteration, withIndex() function is used.
要访问迭代中元素的索引和值,请使用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循环 (Kotlin forEach loop)
ForEach loop repeats a set of statements for each iterable as shown below.
ForEach循环为每个可迭代项重复一组语句,如下所示。
(2..5).forEach{
println(it)
}
//or
(2..5).forEach{
i -> println(i)
}
//Following is printed on the console:
2
3
4
5
it is the default iterable variable that holds the value of the current iterator.
In the second case, we’d use our custom variable.
it是默认的可迭代变量,用于保存当前迭代器的值。
在第二种情况下,我们将使用自定义变量。
Kotlin山脉 (Kotlin Range)
We’ve seen in the above sections that .. operators represents a range.
在以上各节中,我们已经看到..运算符代表一个范围。
(2..4).forEach{
println(it)
}
//Following gets printed on the console:
2
3
4
To check whether an element exists or doesn’t exist in a range we use the in and !in keywords as shown below.
要检查某个元素在范围内是否存在,我们使用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")
}
And the following should work the same way. Right?
并且以下应该以相同的方式工作。 对?
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
NO.
The Range .. can’t be used in the reverse order.
This is where we use the downTo keyword.
没有。
范围..不能以相反的顺序使用。
这是我们使用downTo关键字的地方。
The below code would work:
下面的代码将起作用:
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
To exclude the last element from the range we use the keyword until.
为了从范围中排除最后一个元素,我们使用关键字until 。
for (i in 1 until 4) {
print(i)
}
//prints 123
To traverse the range in steps we use the keyword step.
要逐步遍历范围,我们使用关键字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 loop)
while and do-while loops in Kotlin behave the same way as they do in Java.
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打破并继续 (Kotlin break and continue)
break is used to exit the loop there and then.
continue is used to go to the next iteration of the loop.
Kotlin gives us the luxury to attach a label to the break and continue statements to indicate the loop on which their actions are triggered as shown below.
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重覆以及何时 (Kotlin repeat and when)
repeat allows us to execute the statements in the loop N number of times(where N is the number specified as the argument).
The following code snippet would print the group of statements 3 times.
repeat允许我们在循环中执行N次语句(其中N是指定为参数的数字)。
以下代码段将打印该语句组3次。
repeat(3) {
println("Hello World!")
println("Kotlin Control Flow")
}
when in Kotlin is equivalent to switch in other languages, though with a different syntax and more power!
A basic example of when operator is given below.
when在Kotlin相当于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.
}
}
The when operator matches the argument with all the branches. If it matches with none, the else statement is printed. The else statement is similar to default in switch.
when operator can be used to return values too, similar to if else.
when运算符将参数与所有分支匹配。 如果不匹配,则打印else语句。 else语句与switch中的default相似。
when运算符也可以用于返回值,类似于if。
var valueLessThan100 = when(101){
in 1 until 101 -> true
else -> {
false
}
}
print(valueLessThan100) //false
Going further, we can use Any type to check the branch as shown below.
更进一步,我们可以使用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 Control Flow Statements Example)
Summing up the control flow in our Kotlin project, this is how our Kotlin class file looks:
总结我们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") }
}
}
This brings an end to this tutorial
References: Kotlin Official Doc, Range API Doc
本教程到此结束
参考: Kotlin官方文档 , Range API文档
翻译自: https://www.journaldev.com/18483/kotlin-control-flow-if-else-for-while-range
kotlin 循环
更多推荐

所有评论(0)