原文: http://zetcode.com/kotlin/controlflow/

Kotlin 控制流教程展示了如何使用ifwhenwhilefor在 Kotlin 程序中进行控制流。

Kotlin 是在 Java 虚拟机上运行的静态类型的编程语言。

Kotlin 由 JetBrains 创建。 Kotlin 是一种面向对象的函数式编程语言。 Kotlin 被设计为一种务实,简洁,安全且可互操作的编程语言。

Kotlin if条件

if关键字用于创建简单的条件测试。 可以与else关键字结合使用。

kotlin_if.kt

  1. package com.zetcode
  2. fun main() {
  3. print("Enter your age: ")
  4. val s_age: String? = readLine()
  5. if (s_age!!.isEmpty()) return
  6. val age:Int = s_age.toInt()
  7. if (age > 18) {
  8. println("You can obtain a driving licence")
  9. } else {
  10. println("You cannot obtain a driving licence")
  11. }
  12. }

在示例中,我们提示输入用户的年龄。 我们读取该值,将其转换为整数,然后存储在变量中。

  1. if (age > 18) {
  2. println("You can obtain a driving licence")
  3. } else {
  4. println("You cannot obtain a driving licence")
  5. }

此条件测试年龄是否大于 18 岁。

Kotlin

可以使用if else if语法创建条件的多个分支。

ifelseif.kt

  1. package com.zetcode
  2. fun main() {
  3. val a = 34
  4. val b = 43
  5. if (a == b) {
  6. println("$a and $b are equal")
  7. } else if (a < b) {
  8. println("$a is less than $b")
  9. } else {
  10. println("$b is less than $a")
  11. }
  12. }

在示例中,我们使用if else if来确定两个值是否相等或更大或更小。

Kotlin if表达式

Kotlin 的if是一个表达式,即它返回一个值。

if_expression.kt

  1. package com.zetcode
  2. fun main() {
  3. val a = 34
  4. val b = 43
  5. val max = if (a > b) a else b
  6. println("max of $a and $b is $max")
  7. }

该示例使用if表达式返回两个值中的最大值。

when表达式

Kotlin 的when表达式用于评估多个条件。 它是 Java switch语句的更强大版本。

when关键字将其参数顺序与所有分支匹配,直到满足某些分支条件为止。 它既可以用作表达式也可以用作语句。

when_expression.kt

  1. package com.zetcode
  2. import java.util.Random
  3. fun main() {
  4. val r:Int = Random().nextInt(10) - 5
  5. when {
  6. r < 0 -> println("negative value")
  7. r == 0 -> println("zero")
  8. r > 0 -> println("positive value")
  9. }
  10. }

在示例中,我们生成一个随机数。 基于随机值,我们将消息打印到控制台。

Kotlin while循环

while关键字用于创建循环。 它运行直到满足给定条件。

while_loop.kt

  1. package com.zetcode
  2. fun main() {
  3. var i:Int = 0
  4. while(i < 10) {
  5. i++
  6. println("i is $i")
  7. }
  8. println(i)
  9. }

该示例使用while循环从一到十打印值。

  1. while(i < 10) {

只要i变量小于 10,就一直在运行while条件。

Kotlin for循环

使用 Kotlin 的for循环,我们可以创建比while更容易创建的循环。

for_loop.kt

  1. package com.zetcode
  2. fun main() {
  3. val seasons = arrayOf("Spring", "Summer", "Autumn", "Winter")
  4. for (season in seasons) {
  5. println(season)
  6. }
  7. for (i in 1..15) println(i)
  8. }

在示例中,我们使用for关键字对字符串数组和整数范围进行迭代。

在本教程中,我们介绍了 Kotlin 中的控制流。 您可能也对相关教程感兴趣: Kotlin 字符串教程Kotlin 数组教程或列出所有 Kotlin 教程