kotlin when 表达式

when将它的参数和所有分支条件顺序比较,直到某个分支满足条件。

记录下when使用的几种方式。

when类似于其他语言的switch:

when (x) {
    1 -> print("x == 10")
    2 -> print("x == 20")
    else -> { // 注意这个块
        print("x 不是 10 ,也不是 20")
    }
}

在 when 中,else 同 switch 的 default。如果其他分支都不满足条件将会求值 else 分支。

when (x) {
    0, 1 -> print("x == 0 or x == 1")
    else -> print("otherwise")
}

判断一个值在不在一个区间,用 in

when (x) {
    in 1..10 -> print("x is in the range")
    in validNumbers -> print("x is valid")
    !in 10..20 -> print("x is outside the range")
    else -> print("none of the above")
}

判断一个值是是不是特定类型,用is

fun hasPrefix(x: Any) = when(x) {
    is String -> x.startsWith("prefix")
    else -> false
}

when 也可以用来取代 if-else if链。 如果不提供参数,所有的分支条件都是简单的布尔表达式,而当一个分支的条件为真时则执行该分支:

when {
    x.isOdd() -> print("x is odd")
    x.isEven() -> print("x is even")
    else -> print("x is funny")
}

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Kotlin中的when表达式是一种强大的条件控制结构,类似于其他编程语言中的switch语句。它可以根据不同的条件执行不同的代码块。下面是Kotlin中when表达式的用法: 1. 基本用法: 当需要根据一个变量的值来执行不同的代码块时,可以使用when表达式。例如: ```kotlin val x = 5 when (x) { 1 -> println("x is 1") 2 -> println("x is 2") else -> println("x is neither 1 nor 2") } ``` 当x的值为1时,输出"x is 1";当x的值为2时,输出"x is 2";否则输出"x is neither 1 nor 2"。 2. 多个条件匹配: 可以在一个when表达式中匹配多个条件。例如: ```kotlin val y = 3 when (y) { 1, 2 -> println("y is either 1 or 2") in 3..5 -> println("y is between 3 and 5") else -> println("y is neither 1 nor 2, nor between 3 and 5") } ``` 当y的值为1或2时,输出"y is either 1 or 2";当y的值在3到5之间时,输出"y is between 3 and 5";否则输出"y is neither 1 nor 2, nor between 3 and 5"。 3. 使用表达式作为条件: 当需要根据表达式的结果来执行不同的代码块时,可以将表达式作为when的条件。例如: ```kotlin val z = 7 when { z < 0 -> println("z is negative") z > 0 -> println("z is positive") else -> println("z is zero") } ``` 当z小于0时,输出"z is negative";当z大于0时,输出"z is positive";否则输出"z is zero"。 以上是Kotlin中when表达式的基本用法和常见用法。如果还有其他问题,请继续提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

开开心心everyday

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值