跳转到内容

Kotlin When表达式

来自代码酷


Kotlin When表达式是Kotlin语言中一种强大的条件控制结构,用于替代传统的`switch-case`语句,并提供了更灵活的模式匹配功能。它不仅可以匹配常量值,还能检查类型、范围条件,甚至支持智能类型转换。本教程将详细介绍其语法、特性和实际应用场景。

基本语法[编辑 | 编辑源代码]

`when`表达式的基本结构如下:

when (表达式) {
    1 -> 执行代码1
    2 -> 执行代码2
    else -> 默认执行代码
}

简单示例[编辑 | 编辑源代码]

fun describeNumber(number: Int): String {
    return when (number) {
        1 -> "One"
        2 -> "Two"
        3 -> "Three"
        else -> "Unknown"
    }
}

fun main() {
    println(describeNumber(2)) // 输出: Two
    println(describeNumber(5)) // 输出: Unknown
}

高级特性[编辑 | 编辑源代码]

多条件匹配[编辑 | 编辑源代码]

可以同时匹配多个条件:

when (x) {
    0, 1 -> print("x是0或1")
    in 2..10 -> print("x在2到10之间")
    !in 20..30 -> print("x不在20到30之间")
    else -> print("其他情况")
}

类型检查[编辑 | 编辑源代码]

`when`可以结合`is`进行类型检查:

fun checkType(obj: Any): String {
    return when (obj) {
        is String -> "字符串长度: ${obj.length}"
        is Int -> "整数: $obj"
        is Double -> "双精度浮点数: $obj"
        else -> "未知类型"
    }
}

无参形式[编辑 | 编辑源代码]

`when`可以不带参数,此时分支条件必须是布尔表达式:

when {
    x.isOdd() -> print("x是奇数")
    x.isEven() -> print("x是偶数")
    else -> print("x不是整数")
}

实际应用案例[编辑 | 编辑源代码]

状态机处理[编辑 | 编辑源代码]

stateDiagram [*] --> Idle Idle --> Processing: 收到请求 Processing --> Success: 处理成功 Processing --> Error: 处理失败 Success --> Idle Error --> Idle

使用`when`处理状态转换:

fun handleState(currentState: State, event: Event): State {
    return when (currentState) {
        is Idle -> when (event) {
            is RequestReceived -> Processing(event.data)
            else -> currentState
        }
        is Processing -> when (event) {
            is Success -> Idle
            is Failure -> Error(event.error)
            else -> currentState
        }
        is Error -> Idle
    }
}

表达式返回值[编辑 | 编辑源代码]

`when`可以作为表达式使用,返回最后执行的分支的值:

val result = when (val response = apiCall()) {
    is Success -> response.data
    is Error -> throw IllegalStateException(response.message)
}

数学公式示例[编辑 | 编辑源代码]

当需要根据输入值计算不同数学函数时: f(x)={x2当 x02x+1当 0<x10log(x)其他情况

Kotlin实现:

fun calculate(x: Double): Double = when {
    x <= 0 -> x.pow(2)
    x <= 10 -> 2 * x + 1
    else -> ln(x)
}

性能考虑[编辑 | 编辑源代码]

Kotlin编译器会将`when`表达式优化为:

  • 对于少量分支(通常≤5):转换为`if-else`链
  • 对于常量匹配:可能编译为`tableswitch`或`lookupswitch`字节码
  • 对于复杂条件:保持为条件判断链

最佳实践[编辑 | 编辑源代码]

1. 优先使用`when`而非嵌套的`if-else` 2. 确保覆盖所有可能情况(或使用`else`分支) 3. 对于枚举类型,可以省略`else`分支(如果已覆盖所有枚举值) 4. 利用智能转换简化类型检查代码

常见错误[编辑 | 编辑源代码]

页面模块:Message box/ambox.css没有内容。

通过掌握`when`表达式,Kotlin开发者可以编写更简洁、更安全的条件逻辑代码。这种结构的多功能性使其成为Kotlin控制流中最常用的工具之一。