📜  Kotlin 当表达

📅  最后修改于: 2022-05-13 01:54:49.881000             🧑  作者: Mango

Kotlin 当表达

在 Kotlin 中, when替换了Java等其他语言的switch运算符。当满足某些条件时,需要执行某个代码块。 when表达式的参数与所有分支一一比较,直到找到匹配项。找到第一个匹配项后,它到达 when 块的末尾并执行 when 块旁边的代码。与Java或任何其他编程语言中的 switch case 不同,我们不需要在每个 case 结束时使用 break 语句。在 Kotlin 中, when可以有两种使用方式:

  • 当作为陈述
  • 当作为表达式

when作为语句与else一起使用

when可以用作带有或不带有else分支的语句。如果用作语句,则将所有单个分支的值顺序与参数进行比较,并执行条件匹配的相应分支。如果没有一个分支满足条件,那么它将执行 else 分支。

Kotlin
import java.util.Scanner;
fun main(args: Array) {
    var reader = Scanner(System.`in`)
    print("Enter any largebody:")
    var lb = reader.next()
 
    when(lb) {
        "Sun" -> println("Sun is a Star")
        "Moon" -> println("Moon is a Satellite")
        "Earth" -> println("Earth is a planet")
         else -> println("I don't know anything about it")
    }
}


Kotlin
import java.util.Scanner;
fun main(args: Array) {
    var reader = Scanner(System.`in`)
    print("Enter name:")
    var lb = reader.next()
 
    when(lb) {
        "Sun" -> println("Sun is a Star")
        "Moon" -> println("Moon is a Satellite")
        "Earth" -> println("Earth is a planet")
    }
}


Kotlin
import java.util.Scanner;
fun main(args: Array) {
    var reader = Scanner(System.`in`)
    print("Enter the month number:")
    var monthOfYear = reader.nextInt()
    var month = when(monthOfYear){
        1->"January"
        2->"February"
        3->"March"
        4->"April"
        5->"May"
        6->"June"
        7->"July"
        8->"August"
        9->"September"
        10->"October"
        11->"November"
        12->"December"
        else -> {
            println("Not a month of year")
        }
    }
    println(month)
}


Kotlin
import java.util.Scanner;
fun main(args: Array) {
    var reader = Scanner(System.`in`)
    print("Enter name of planet: ")
    var name = reader.next()
    when(name) {
        "Mercury","Earth","Mars","Jupiter"
            ,"Neptune","Saturn","Venus","Uranus" -> println("Planet")
        else -> println("Neither planet nor star")
    }
}


Kotlin
import java.util.Scanner;
 
fun main(args: Array) {
    var reader = Scanner(System.`in`)
    print("Enter the month number of year: ")
    var num = reader.nextInt()
    when(num){
        in 1..3 -> println("It is spring season")
        in 4..6 -> println("It is summer season")
        in 7..8 ->println("It is rainy season")
        in 9..10 -> println("It is autumn season")
        in 11..12 -> println("It is winter season")
        !in 1..12 ->println("Enter valid month of year")
    }
}


Kotlin
fun main(args: Array) {
    var num: Any = "GeeksforGeeks"
    when(num){
        is Int -> println("It is an Integer")
        is String -> println("It is a String")
        is Double -> println("It is a Double")
    }
}


Kotlin
fun isOdd(x: Int) = x % 2 != 0
fun isEven(x: Int) = x % 2 == 0
 
fun main(args: Array) {
    var num = 8
    when{
        isOdd(num) ->println("Odd")
        isEven(num) -> println("Even")
        else -> println("Neither even nor odd")
    }
}


Kotlin
fun hasPrefix(company: Any) = when (company) {
    is String -> company.startsWith("GeeksforGeeks")
    else -> false
}
 
fun main(args: Array) {
    var company = "GeeksforGeeks a computer science portal"
    var result = hasPrefix(company)
    if(result) {
        println("Yes, string started with GeeksforGeeks")
    }
    else {
        println("No, String does not started with GeeksforGeeks")
    }
}


输出:

Enter any largebody: Sun
Sun is a Star

Enter any largebody: Mars
I don't know anything about it

使用 when 作为语句而不使用else

我们可以将 when 用作没有else分支的语句。如果用作语句,则将所有单个分支的值与参数顺序进行比较,并执行条件匹配的相应分支。如果没有一个分支满足条件,那么它只是退出块而不向系统输出打印任何内容。

科特林

import java.util.Scanner;
fun main(args: Array) {
    var reader = Scanner(System.`in`)
    print("Enter name:")
    var lb = reader.next()
 
    when(lb) {
        "Sun" -> println("Sun is a Star")
        "Moon" -> println("Moon is a Satellite")
        "Earth" -> println("Earth is a planet")
    }
}

输出:

Enter name: Mars
Process finished with exit code 0

使用 when 作为表达式

如果用作表达式,则满足条件的分支的值将是整体表达式的值。作为表达式when返回与参数匹配的值,我们可以将其存储在变量中或直接打印。

科特林

import java.util.Scanner;
fun main(args: Array) {
    var reader = Scanner(System.`in`)
    print("Enter the month number:")
    var monthOfYear = reader.nextInt()
    var month = when(monthOfYear){
        1->"January"
        2->"February"
        3->"March"
        4->"April"
        5->"May"
        6->"June"
        7->"July"
        8->"August"
        9->"September"
        10->"October"
        11->"November"
        12->"December"
        else -> {
            println("Not a month of year")
        }
    }
    println(month)
}

输出:

Enter the month number:8
August

如果参数不满足任何分支条件,则执行 else 分支。作为表达式,else 分支是强制性的,除非编译器能够证明所有可能的情况都被分支条件覆盖。如果我们不能使用 else 分支,它将给出编译器错误。

Error:(6, 17) Kotlin: 'when' expression must be exhaustive, add necessary 'else' branch

Kotlin 中 block 的不同使用方式

使用逗号将多个分支合二为一:

我们可以在一个分支中使用多个分支,用逗号分隔。当一些分支共享公共逻辑时,我们可以将它们组合在一个分支中。在下面的示例中,我们需要检查输入的大体是否为行星,因此我们将所有行星的名称组合在一个分支中。除了行星名称之外,输入的任何内容都将执行 else 分支。

科特林

import java.util.Scanner;
fun main(args: Array) {
    var reader = Scanner(System.`in`)
    print("Enter name of planet: ")
    var name = reader.next()
    when(name) {
        "Mercury","Earth","Mars","Jupiter"
            ,"Neptune","Saturn","Venus","Uranus" -> println("Planet")
        else -> println("Neither planet nor star")
    }
}

输出:

Enter name of planet: Earth
Planet

检查范围内的输入值与否:

使用in!in运算符,我们可以检查 when 块中传入的参数范围。 Kotlin 中的“in”运算符用于检查特定变量或属性是否存在于某个范围内。如果参数位于特定范围内,则 in运算符返回 true,如果参数不在特定范围内,则 !in 返回 true。

科特林

import java.util.Scanner;
 
fun main(args: Array) {
    var reader = Scanner(System.`in`)
    print("Enter the month number of year: ")
    var num = reader.nextInt()
    when(num){
        in 1..3 -> println("It is spring season")
        in 4..6 -> println("It is summer season")
        in 7..8 ->println("It is rainy season")
        in 9..10 -> println("It is autumn season")
        in 11..12 -> println("It is winter season")
        !in 1..12 ->println("Enter valid month of year")
    }
}

输出:

Enter the month number of year: 5
It is summer season

Enter the month number of year: 14
Enter valid month of year

检查给定变量是否属于某种类型:

使用is!is运算符,我们可以检查在 when 块中作为参数传递的变量的类型。如果变量是 Integer 类型,则 is Int 返回 true,否则返回 false。

科特林

fun main(args: Array) {
    var num: Any = "GeeksforGeeks"
    when(num){
        is Int -> println("It is an Integer")
        is String -> println("It is a String")
        is Double -> println("It is a Double")
    }
}

输出:

It is a String

使用 when 代替 if-else-if 链:

我们可以使用 when 作为 if-else-if 的替代品。如果没有提供参数,则分支条件只是布尔表达式,并且仅在条件为真时执行分支:

科特林

fun isOdd(x: Int) = x % 2 != 0
fun isEven(x: Int) = x % 2 == 0
 
fun main(args: Array) {
    var num = 8
    when{
        isOdd(num) ->println("Odd")
        isEven(num) -> println("Even")
        else -> println("Neither even nor odd")
    }
}

输出:

Even

检查字符串是否包含特定的前缀或后缀:

我们还可以通过以下方法检查给定字符串中的前缀或后缀。如果字符串包含前缀或后缀,那么它将返回布尔值 true 否则返回 false。

科特林

fun hasPrefix(company: Any) = when (company) {
    is String -> company.startsWith("GeeksforGeeks")
    else -> false
}
 
fun main(args: Array) {
    var company = "GeeksforGeeks a computer science portal"
    var result = hasPrefix(company)
    if(result) {
        println("Yes, string started with GeeksforGeeks")
    }
    else {
        println("No, String does not started with GeeksforGeeks")
    }
}

输出:

Yes, string started with GeeksforGeeks