1

I want to assign a variable in Kotlin with 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
}

But IntelliJ says it would always return the second null value.

How can I achieve it that the variable clickedBlock will be assigned with block (and not null) if the if statement inside of the forEach loop is true without having to introduce another variable?

0

1 Answer 1

4

You can wrap this in a run function

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
}

but I think it would be better to do this:

Action.RIGHT_CLICK_AIR -> p.getLineOfSight(null, 5).find { block -> block.type != Material.VOID_AIR }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.