I was hoping that a null-checking filter on a coll...
# getting-started
v
I was hoping that a null-checking filter on a collection would safely return only the non-null elements, that I could then check for other values. Unfortunately, intelliJ/compiler not accepting this: `
Copy code
hexes.filter { it.hexData != null }
    .first { it.hexData.row == newHexData.row && it.hexData.column == newHexData.column }
Any suggestions? Ideally without creating a new list of hexes?
j
In this case you can simply move the null check into the
first
lambda, and ditch the
filter
It's also more efficient this way because you don't create an intermediate collection
v
Like this?
Copy code
hexes.first { it.hexData != null && it.hexData.row == newHexData.row && it.hexData.column == newHexData.column }
👌 1
I've still got nullables to deal with because it's a "mutable property that could have been changed by this time". It won't have been, so that's more
!!
for me to add 😞 It's for a game written with Godot, so there are loads of
!!
already.
y
hexes.mapNotNull { it.hexData }.first { it.row == newHexData.row && it.column == newHexData.column }
d
That's assuming they only want hexData, not the entire outer object.
🤦🏼 1
Copy code
hexes.first {
   it.hexData?.run { row == newHJexData.row && column = newHexData.column } == true
}
v
Hmm! I do need the outer object. I use
?.let
often enough, tend to forget about
run
.
d
you could also use ?.let, but
it
outside would be different than
it
inside, and that's just ugly 😉
Either way, I would consider extracting that into a function in HexData
Copy code
class HexData(...) {
   fun isSameCellAs(other: HexData):Boolean { ... }
}
Then :
hexes.first { it.hexData?.isSameCellAs(newHexData) }
3