gpt4 book ai didi

kotlin - Kotlin “return”声明何时分配变量

转载 作者:行者123 更新时间:2023-12-02 13:07:42 25 4
gpt4 key购买 nike

我想在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表示它将始终返回第二个null值。

如果在forEach循环内的if语句为true 而不引入另一个变量,我如何实现为 clickedBlock变量分配块(而不是null)?

最佳答案

您可以将其包装在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 }

关于kotlin - Kotlin “return”声明何时分配变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61527759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com