kotlin中的when

今天看到一个kotlin源码,有点奇怪:

kotlin 复制代码
public fun <T> Comparator<T>.reversed(): Comparator<T> = when (this) {
    is ReversedComparator -> this.comparator
    NaturalOrderComparator -> @Suppress("UNCHECKED_CAST") (ReverseOrderComparator as Comparator<T>)
    ReverseOrderComparator -> @Suppress("UNCHECKED_CAST") (NaturalOrderComparator as Comparator<T>)
    else -> ReversedComparator(this)
}

这里很奇怪,为什么第一个分支有is,后面两个没有is,还能这样的吗?这是因为kotlinwhen同时支持多种不同判断,上面代码实际上等同于:

kotlin 复制代码
if (this is ReversedComparator) {
    ...
} else if (this == NaturalOrderComparator) {
    ...
} else if (this == ReverseOrderComparator) {
    ...
}

第一个是判断类型,后面两个是判断对象相等,因为那两个对象是单例(object NaturalOrderComparator),所以直接写了类名,感觉以为是在判断类型,其实是判断是否相等。when支持同时使用各种判断,示例如下:

kotlin 复制代码
when (x) {
    1 -> ...	// 值匹配
    "abc" -> ... // 值匹配
    MySingleton -> ... // 值匹配,单例
    99, 999, 9999 -> ... // 匹配多个值
    in 1..10 -> ... // 匹配在某个区间
    !in 11..20 -> ... // 匹配不在某个区间
    is Int -> ... // 匹配是某个类型
    !is String -> ... // 匹配不是某个类型
}

如果想要表达大于或小于某个值,或者想要任意表达式,则when后面不能加括号,示例如下:

kotlin 复制代码
when {
    x > 10 -> println("")
    a is String -> println("")
}

这个写法更强大,没有了括号的限制,只要是一个Boolean表达式就可以用作它的分支。

相关推荐
JohnnyDeng942 小时前
【Android】Android 包体积优化:R8/ProGuard 深度配置全攻略
android·性能优化·kotlin·jetpack
逐光老顽童11 小时前
用 Jetpack Compose + MVI 开发了一个 Authenticator 双因素认证应用
架构·kotlin
JohnnyDeng941 天前
【Android】Hilt 依赖注入:原理与最佳实践
android·kotlin·mvvm·hilt
杉氧1 天前
Kotlin 协程深度解析④:架构实战——在 MVVM/MVI 中的进阶应用
android·kotlin
杉氧1 天前
Kotlin 协程深度解析③:流式编程——Flow 的响应式进化
android·kotlin
Coffeeee1 天前
Android16升级,预测性返回适配起来到底难不难
android·程序员·kotlin
QING6181 天前
Kotlin 协程新手指南 —— 结构化并发
android·kotlin·android jetpack
Kapaseker2 天前
为什么 Java 要废弃 Thread.stop()?看完这篇你就懂了
android·kotlin
唐青枫2 天前
Kotlin run 详解:把对象操作收进作用域,再把结果带出来
kotlin
杉氧2 天前
Kotlin 协程深度解析②:生存指南——掌握结构化并发的生命线
android·kotlin