【问题标题】:Execute and Return from Code Block (after Elvis operator)从代码块执行和返回(在 Elvis 运算符之后)
【发布时间】:2019-05-04 01:02:16
【问题描述】:

我真的不知道如何命名标题,因此我将尽可能地解释它:

val a = b ?: ({
    val temp = c.evaluate()
    store(temp)
    temp // returns temp to the lambda, which will set `a` to `temp` if `b` is null 
})()

1:什么有效,我目前使用什么

这很好用,但我理想中想要做的只是使用代码块而不是将 lambda 传递给函数 (({})) 然后对其进行评估。在我的想象中,它看起来像这样:

val a = b ?: {
    val temp = c.evaluate()
    store(temp)
    temp // returns temp to the lambda, which will set `a` to `temp` if `b` is null 
}

2:我想要什么

以上内容有效。我其实只是在寻找更好的写法1

【问题讨论】:

    标签: kotlin


    【解决方案1】:

    你可以使用run函数:

    val a = b ?: run {
        val temp = c.evaluate()
        store(temp)
        temp
    }
    

    【讨论】:

    【解决方案2】:

    你可以使用also函数:

    val a = b ?: c.evaluate().also { store(it) }
    

    这允许您在将值作为also 的结果传递的同时对值进行操作

    【讨论】:

      猜你喜欢
      • 2018-01-10
      • 1970-01-01
      • 1970-01-01
      • 2011-06-26
      • 2021-08-25
      • 2019-12-03
      • 2015-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多