Kotlin "return "语句用于当变量赋值时

问题描述 投票:1回答:1

我想在Kotlin中用when赋一个变量。

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说它总是会返回第二个空值。

如何才能实现让变量 clickedBlock 如果forEach循环中的if语句为真,则会被分配给block(而不是null) 而不需要引入另一个变量?

kotlin
1个回答
4
投票

你可以把它包装在一个 运行 功能

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 }
© www.soinside.com 2019 - 2024. All rights reserved.