`.mapNotNull { it.foo }.filter { barFunction(it) }...
# getting-started
k
.mapNotNull { it.foo }.filter { barFunction(it) }
👍 2
d
this would give me a list of
foo
. I had intended to get a list of elements of
someList
p
Can you just merge two `filter`s?
Copy code
someList
.filter(it.foo != null && barFunction(it.foo))
if
foo
is
val
without custom getter, then this should work
👍 2
d
yes that would work, thanks
Not sure if I like it better than using a double filter with !!, but I guess it is a bit cleaner
t
Could you make
barFunction
an extension method on a nullable receiver of the type in your list?
Then you could collapse it to:
Copy code
someList
.filter(it.foo.barFunction())
p
Or if receiver is not nullable, then
Copy code
someList
.filter(it.foo?.barFunction() == true)
t
I mean make the extension on a nullable receiver, something like:
Copy code
fun Fun?.barFunction() = this != null && barFunction(this)
Everything is null-safe and the call site is really clean
k
Except that the behavior wanted on null may be different depending on the caller.
t
Then that caller can define another extension method
d
@tddmonkey good idea! In my case it would not work, unfortunately, as
barFunction
is already a method on a wrapper to a library. I guess my only option left is to overload barFunction on that wrapper
t
Hey @dG - I’m not sure if I’m being clear here. What I mean is in the scope of your filter method, define a private extension method. The fact it exists on a wrapper is fine!
d
Aha! Thanks, I did not get that, now I do!
n
.filter { foo?.let { barfunction(it) } ?: false }
would be my sugestion
👍 1