Kotlin when() local variable introduction

孤人 提交于 2019-12-10 13:44:53

问题


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
}

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...
}

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


回答1:


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:

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.

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.

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
    }
}


来源:https://stackoverflow.com/questions/43102797/kotlin-when-local-variable-introduction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!