我想在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) 而不需要引入另一个变量?
你可以把它包装在一个 运行 功能
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 }