Kotlin when()局部变量介绍 [英] Kotlin when() local variable introduction

查看:112
本文介绍了Kotlin when()局部变量介绍的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个称为doHardThings()的昂贵函数,该函数可能返回各种不同的类型,我想根据返回的类型采取措施.在Scala中,这是match构造的常见用法:

Let's say I have an expensive function called doHardThings() which may return various different types, and I would like to take action based on the returned type. In Scala, this is a common use of the match construct:

def hardThings() = doHardThings() match {
     case a: OneResult => // Do stuff with a
     case b: OtherResult => // Do stuff with b
}

我正在努力弄清楚如何在Kotlin中干净地执行此操作,而不会为doHardThings()引入临时变量:

I'm struggling to figure out how to do this cleanly in Kotlin without introducing a temporary variable for doHardThings():

fun hardThings() = when(doHardThings()) {
     is OneResult -> // Do stuff... with what?
     is OtherResult -> // Etc...
}

此常见用例的惯用Kotlin模式是什么?

What is an idiomatic Kotlin pattern for this common use case?

推荐答案

更新:现在可以实现了,来自Kotlin 1.3 .语法如下:

Update: this is now possible, from Kotlin 1.3. Syntax is as follows:

fun hardThings() = when (val result = doHardThings()) {
     is OneResult -> // use result
     is OtherResult -> // use result some other way
}


旧答案:


Old answer:

我认为您只需要为该函数添加一个块体并将操作结果保存到局部变量即可.诚然,这不如Scala版本那么整齐.

I think you'll just have to have a block body for the function and save the result of the operation to a local variable. Admittedly, this is not as neat as the Scala version.

whenis检查一起使用的目的是传递一个变量,然后在分支内使用相同的变量,因为如果通过检查,它将被智能地转换为被检查的类型您可以轻松访问其方法和属性.

The intended use of when with is checks is to pass in a variable and then use that same variable inside your branches, because then if it passes a check, it gets smart cast to the type it was checked for and you can access its methods and properties easily.

fun hardThings() {
    val result = doHardThings()
    when(result) {
        is OneResult ->   // result smart cast to OneResult
        is OtherResult -> // result smart cast to OtherResult
    }
}

您可以以某种方式围绕您的操作编写某种包装器,以便它只对它进行一次评估,否则返回缓存的结果,但这可能不值得它带来的复杂性.

You could write some sort of wrapper around your operation somehow so that it only evaluates it once and otherwise returns the cached result, but it's probably not worth the complications that it introduces.

通过@ mfulton26创建变量的另一种解决方案是使用let():

Another solution for creating the variable by @mfulton26 is to use let():

fun hardThings() = doHardThings().let {
    when(it) {
        is OneResult ->   // it smart cast to OneResult
        is OtherResult -> // it smart cast to OtherResult
    }
}

这篇关于Kotlin when()局部变量介绍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆