假设我有一个名为 doHardThings()
的昂贵函数这可能会返回各种不同的类型,我想根据返回的类型采取行动。在 Scala 中,这是 match
的常见用法。构造:
def hardThings() = doHardThings() match {
case a: OneResult => // Do stuff with a
case b: OtherResult => // Do stuff with b
}
我正在努力弄清楚如何在 Kotlin 中干净利落地做到这一点而不为
doHardThings()
引入临时变量:fun hardThings() = when(doHardThings()) {
is OneResult -> // Do stuff... with what?
is OtherResult -> // Etc...
}
这个常见用例的惯用 Kotlin 模式是什么?
最佳答案
更新:现在可以了,from Kotlin 1.3 .语法如下:
fun hardThings() = when (val result = doHardThings()) {
is OneResult -> // use result
is OtherResult -> // use result some other way
}
旧答案:
我认为您只需要为函数创建一个块体并将操作结果保存到局部变量即可。诚然,这不像 Scala 版本那么简洁。
when
的预期用途与 is
检查是传入一个变量,然后在你的分支中使用相同的变量,因为如果它通过检查,它会智能地转换为它被检查的类型,你可以轻松访问它的方法和属性。fun hardThings() {
val result = doHardThings()
when(result) {
is OneResult -> // result smart cast to OneResult
is OtherResult -> // result smart cast to OtherResult
}
}
您可以以某种方式围绕您的操作编写某种包装器,以便它只计算一次,否则返回缓存的结果,但这可能不值得它引入的复杂性。
通过@mfulton26 创建变量的另一种解决方案是使用
let()
:fun hardThings() = doHardThings().let {
when(it) {
is OneResult -> // it smart cast to OneResult
is OtherResult -> // it smart cast to OtherResult
}
}
关于pattern-matching - Kotlin when() 局部变量介绍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43102797/