https://kotlinlang.org logo
Title
k

karelpeeters

02/01/2019, 11:15 AM
.mapNotNull { it.foo }.filter { barFunction(it) }
👍 2
d

dG

02/01/2019, 11:19 AM
this would give me a list of
foo
. I had intended to get a list of elements of
someList
p

Pavlo Liapota

02/01/2019, 11:22 AM
Can you just merge two `filter`s?
someList
.filter(it.foo != null && barFunction(it.foo))
if
foo
is
val
without custom getter, then this should work
👍 2
d

dG

02/01/2019, 11:24 AM
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

tddmonkey

02/01/2019, 11:45 AM
Could you make
barFunction
an extension method on a nullable receiver of the type in your list?
Then you could collapse it to:
someList
.filter(it.foo.barFunction())
p

Pavlo Liapota

02/01/2019, 11:47 AM
Or if receiver is not nullable, then
someList
.filter(it.foo?.barFunction() == true)
t

tddmonkey

02/01/2019, 11:49 AM
I mean make the extension on a nullable receiver, something like:
fun Fun?.barFunction() = this != null && barFunction(this)
Everything is null-safe and the call site is really clean
k

karelpeeters

02/01/2019, 11:51 AM
Except that the behavior wanted on null may be different depending on the caller.
t

tddmonkey

02/01/2019, 11:53 AM
Then that caller can define another extension method
d

dG

02/01/2019, 12:06 PM
@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

tddmonkey

02/01/2019, 12:12 PM
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

dG

02/01/2019, 12:16 PM
Aha! Thanks, I did not get that, now I do!
n

Nikky

02/01/2019, 1:57 PM
.filter { foo?.let { barfunction(it) } ?: false }
would be my sugestion
👍 1