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.
![kotlin control flow, kotlin if else, kotlin for loop](https://cdn.journaldev.com/wp-content/uploads/2018/02/kotlin-control-flow.png)
通过在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")