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表达式就可以用作它的分支。

相关推荐
ai2work2 天前
ch23 综合复刻:从零做一个最小可用版本(capstone)
kotlin
ai2work2 天前
ch21 签名、校验与发版
kotlin
JMchen2 天前
属性动画原理与高级动画实现
android·kotlin·canvas
Android打工仔2 天前
Kotlin 协程源码解析:协程是如何切换线程的?
android·kotlin
ai2work2 天前
附录 D 速查索引与阅读指南
kotlin
ai2work2 天前
ch22 诊断方法论:三个真实事故的根因分析
kotlin
Kapaseker2 天前
你有搞明白 Volatile 什么意思吗?
android·kotlin
alexhilton3 天前
藏在设备上的秘密,终究藏不住
android·kotlin·android jetpack
ai2work3 天前
ch15 加载模型与初始化上下文
kotlin
hai_android3 天前
Kotlin / Android 常用函数使用示例手册
android·java·kotlin