假设我有一个昂贵的函数,名为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 模式是什么?
更新:现在这是可能的,来自科特林 1.3 https://kotlinlang.org/docs/reference/whatsnew13.html#capturing-when-subject-in-a-variable。语法如下:
fun hardThings() = when (val result = doHardThings()) {
is OneResult -> // use result
is OtherResult -> // use result some other way
}
旧答案:
我认为您只需要为该函数提供一个块体并将操作结果保存到局部变量即可。不可否认,这并不像 Scala 版本那么整洁。
预期用途when
with 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
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)