在上一章节中,我们了解了Kotlin系统中可用的不同类型的数据类型。在本章节中,我们将讨论Kotlin中可用的不同类型的控制流机制。

If - Else

Kotlin是一种函数式语言,因此像其他函数式语言一样,在Kotlin中“if”是一个表达式,而不是关键字。该表达式“if”会在必要时返回一个值。与其他编程语言一样,“if-else”块用作初始条件检查运算符。在下面的示例中,我们将比较两个变量并相应地提供所需的输出。

Live Demo

  1. fun main(args: Array<String>) {
  2. val a:Int = 5
  3. val b:Int = 2
  4. var max: Int
  5. if (a > b) {
  6. max = a
  7. } else {
  8. max = b
  9. }
  10. print("Maximum of a or b is " +max)
  11. // As expression
  12. // val max = if (a > b) a else b
  13. }

上述代码在浏览器中产生了以下输出结果。我们的示例还包含另一行代码,描述如何将“If”语句用作表达式。

a或b的最大值为5

Use of When

如果您熟悉其他编程语言,那么您可能听说过术语switch语句,它基本上是一种条件运算符,可以在特定变量上应用多个条件。“when”运算符将变量值与分支条件进行匹配。如果满足分支条件,则会执行该范围内的语句。在下面的示例中,我们将进一步了解Kotlin中的“when”。

Live Demo

  1. fun main(args: Array<String>) {
  2. val x:Int = 5
  3. when (x) {
  4. 1 -> print("x = = 1")
  5. 2 -> print("x = = 2")
  6. else -> { // Note the block
  7. print("x is neither 1 nor 2")
  8. }
  9. }
  10. }

上述代码在浏览器中产生了以下输出结果。

x 既不是 1 也不是 2

在上述示例中,Kotlin编译器将x的值与给定的分支进行匹配。如果它没有匹配任何分支,则会执行else部分。实际上,when等效于多个if块。Kotlin为开发人员提供了另一种灵活性,即在同一行中通过在检查中提供“,”来提供多个检查。让我们修改上述示例如下。

Live Demo

  1. fun main(args: Array<String>) {
  2. val x:Int = 5
  3. when (x) {
  4. 1,2 -> print(" Value of X either 1,2")
  5. else -> { // Note the block
  6. print("x is neither 1 nor 2")
  7. }
  8. }
  9. }

Run the same in the browser, which will yield the following output in the browser. x is neither 1 nor 2

For Loop

Loop is such an invention that provides the flexibility to iterate through any kind of data structure. Like other programming languages, Kotlin also provides many kinds of Looping methodology, however, among them “For” is the most successful one. The implementation and use of For loop is conceptually similar to Java for loop. The following example shows how we can use the same in real-life examples.

Live Demo

  1. fun main(args: Array<String>) {
  2. val items = listOf(1, 2, 3, 4)
  3. for (i in items) println("values of the array"+i)
  4. }In the above piece of code, we have declared one list named as items and using for loop we are iterating through that defined list and printing its value in the browser. Following is the output.
  5. values of the array1
  6. values of the array2
  7. values of the array3
  8. values of the array4Following is another example of code, where we are using some library function to make our development work easier than ever before.<br />[ Live Demo](http://tpcg.io/MSOn9d)
  9. fun main(args: Array<String>) {
  10. val items = listOf(1, 22, 83, 4)
  11. for ((index, value) in items.withIndex()) {
  12. println("the element at $index is $value")
  13. }
  14. }

Once we compile and execute the above piece of code in our coding ground, it will yield the following output in the browser. the element at 0 is 1 the element at 1 is 22 the element at 2 is 83 the element at 3 is 4

While Loop and Do-While Loop

While and Do-While work exactly in a similar way like they do in other programming languages. The only difference between these two loops is, in case of Do-while loop the condition will be tested at the end of the loop. The following example shows the usage of the While loop.
Live Demo

  1. fun main(args: Array<String>) {
  2. var x:Int = 0
  3. println("Example of While Loop--")
  4. while(x< = 10) {
  5. println(x)
  6. x++
  7. }
  8. }

The above piece of code yields the following output in the browser. Example of While Loop— 0 1 2 3 4 5 6 7 8 9 10Kotlin also has another loop called Do-While loop, where the loop body will be executed once, only then the condition will be checked. The following example shows the usage of the Do-while loop.
Live Demo

  1. fun main(args: Array<String>) {
  2. var x:Int = 0
  3. do {
  4. x = x + 10
  5. println("I am inside Do block---"+x)
  6. } while(x <= 50)
  7. }

The above piece of code yields the following output in the browser. In the above code, Kotlin compiler will execute the DO block, then it will go for condition checking in while block. I am inside Do block—-10 I am inside Do block—-20 I am inside Do block—-30 I am inside Do block—-40 I am inside Do block—-50 I am inside Do block—-60

Use of Return, Break, Continue

If you are familiar with any programming language, then you must have an idea of different keywords that help us implement good control flow in the application. Following are the different keywords that can be used to control the loops or any other types of control flow.
Return − Return is a keyword that returns some value to the calling function from the called function. In the following example, we will implement this scenario using our Kotlin coding ground.
Live Demo

  1. fun main(args: Array<String>) {
  2. var x:Int = 10
  3. println("The value of X is--"+doubleMe(x))
  4. }
  5. fun doubleMe(x:Int):Int {
  6. return 2*x;
  7. }

In the above piece of code, we are calling another function and multiplying the input with 2, and returning the resultant value to the called function that is our main function. Kotlin defines the function in a different manner that we will look at in a subsequent chapter. For now, it is enough to understand that the above code will generate the following output in the browser.

The value of X is—20Continue & Break − Continue and break are the most vital part of a logical problem. The “break” keyword terminates the controller flow if some condition has failed and “continue” does the opposite. All this operation happens with immediate visibility. Kotlin is smarter than other programming languages, wherein the developer can apply more than one label as visibility. The following piece of code shows how we are implementing this label in Kotlin.

Live Demo

  1. fun main(args: Array<String>) {
  2. println("Example of Break and Continue")
  3. myLabel@ for(x in 1..10) { // appling the custom label
  4. if(x = = 5) {
  5. println("I am inside if block with value"+x+"\n-- hence it will close the operation")
  6. break@myLabel //specifing the label
  7. } else {
  8. println("I am inside else block with value"+x)
  9. continue@myLabel
  10. }
  11. }
  12. }

The above piece of code yields the following output in the browser. Example of Break and Continue I am inside else block with value1 I am inside else block with value2 I am inside else block with value3 I am inside else block with value4 I am inside if block with value5 — hence it will close the operationAs you can see, the controller continues the loop, until and unless the value of x is 5. Once the value of x reaches 5, it starts executing the if block and once the break statement is reached, the entire control flow terminates the program execution.