I have a nullable Int which can be `null`, `1`, `2...
# announcements
l
I have a nullable Int which can be
null
,
1
,
2
and so on. It's named
condition
. I have a list,
listOf(1,2,3,4)
. That's named
stream
. Based of on
condition
I would like to
filter
for
stream
, but only if it's non-
null
. How can I perform a
filter
operation if a condition either is
null
or a value?
if(condition != null) stream.filter(it == condition) else stream
is one solution I suppose but is there a cleaner way?
a
IMO your
if
-version is fine. If you want you can create your own little helper function:
Copy code
inline fun <T> T.runIf(predicate: Boolean, f: (T) -> T) =
    if (predicate)
        f(this)
     else
        this
Copy code
myList.runIf(condition != null) {
    it.filter(it == condition)
}