【问题标题】:Kotlin "return" statement for when variable assignment变量赋值时的 Kotlin“return”语句
【发布时间】:2020-04-30 16:04:36
【问题描述】:

我想在 Kotlin 中分配一个变量:

val clickedBlock: Block? = when (event.action) {
    ...
    Action.RIGHT_CLICK_AIR -> {
        p.getLineOfSight(null, 5).forEach { block ->
            if (block.type != Material.VOID_AIR) {
                block // I want to assign the variable with this
            }
        }
        null // and not always with this
    }
    else -> null
}

但是 IntelliJ 说它总是会返回第二个空值。

如果forEach循环内的if语句为真无需引入另一个变量,我如何实现变量clickedBlock将被分配块(而不是空)?

【问题讨论】:

    标签: kotlin


    【解决方案1】:

    您可以将其包装在 run 函数中

    Action.RIGHT_CLICK_AIR -> run {
        p.getLineOfSight(null, 5).forEach { block ->
            if (block.type != Material.VOID_AIR) {
                return@run block // I want to assign the variable with this
            }
        }
        null
    }
    

    但我认为这样做会更好:

    Action.RIGHT_CLICK_AIR -> p.getLineOfSight(null, 5).find { block -> block.type != Material.VOID_AIR }
    

    【讨论】:

      猜你喜欢
      • 2019-11-24
      • 1970-01-01
      • 2021-08-13
      • 2016-05-17
      • 2020-06-27
      • 1970-01-01
      • 2011-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多