pattern-matching - Kotlin when() 局部变量介绍

标签 pattern-matching kotlin

假设我有一个名为 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/

相关文章:

python - 如何使用python匹配文件中的文件名

scala - 错误: not found: value:::

kotlin - 定义 CoroutineScope 时,Dispatcher.IO + job 会发生什么?

android - android按钮和监听器。我怎样才能使它更短

android - 未设置 PlaceSelectionListener。不会传递任何结果

sql - 如何使用 SQL 识别或识别数据中的模式

函数签名中的 F# 模式匹配

prolog - 在子句头部使用 vars 解构 (Prolog)

kotlin - 检查传递的参数是否是类的类型

java - Corda 节点无法启动并给出错误初始化失败错误代码 1gariof