2

I have a var of type ArrayBuffer.

var selected = new ArrayBuffer[Component](0)

I would like to extract from it the first element which satisfies a given condition.

var res = selected.filter(_.node == neighbour)(0)

I want something like the line above, but in case no element satisfies that condition, I want res to be null. Instead, the code is throwing an error.

How can I get the first element satisfying the condition or null?

1 Answer 1

8

First, use find instead of filter which will return the first one on an Option. Then use orNull to get the value or null if it is missing:

val res = selected.find(_.node == neighbour).orNull

Or you could use filter, headOption, and orNull

val res = selected.filter(_.node == neighbour).headOption.orNull

As a kind of mandatory note when dealing with null: Using Option instead of null is the scala idiomatic and recommended way.

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.