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模式?

我想你只需要有一个函数块体,并将操作的结果保存到局部变量。 诚然,这不像Scala版本那样整洁。

whenis检查的目的是传入一个变量,然后在你的分支中使用同一个变量,因为如果它通过了一个检查,它会被智能转换为检查的类型,你可以访问它的方法和属性很容易。

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