If I have a collection and i want to chain `.filte...
# announcements
f
If I have a collection and i want to chain
.filter
only if a certain condition is true, how do I do that?
Copy code
.apply { if (boolean) filter {} }
does not seem to work
g
You need else condition, just add
else this
Oh, and also you should replace
apply
with
run
Apply doesn't return result of the lamda and used only to modify/use rexeicer
s
if you want call site to be easy to read, just go with an extension function
Copy code
inline fun <T> Iterable<T>.filterIf( applyFilter : Boolean, predicate: (T) -> Boolean ) : List<T> =
        if( applyFilter ) filter( predicate ) else toList()
for more custom support, you could even change the Boolean into a lambda that returns a boolean
though the call site usage would then involve two lambdas within ()