I want to create an extension function to filter a...
# announcements
x
I want to create an extension function to filter a list based on condition x, and if condition x returns an empty list, go for another condition, but I can't figure an idiomatic way to write it; here's what I've got:
more specifically, I want to reuse part of the predicate is my concern
Copy code
private inline fun Iterable<TestObject>.emptyFilterIfNotContained(predicate: (TestObject) -> TestObject): List<TestObject>{
  return filterTo(ArrayList(), predicate).ifEmpty{ filterTo(ArrayList(), {it.b.isEmpty()}
}
but I want b to be variable, as in, be the object that the predicate just compared to
so lets say I called that function with
Copy code
test.emptyFilterIfNotContained { it.b.contains('a')}
then it should check for b, but if I sent it.a.contains in the predicate, it should do it.a.isEmpty()
v
assuming you are comparing string
Copy code
private inline fun Iterable<TestObject>.emptyFilterIfNotContained(getValue:(TestObject)-> String, predicate: (String) -> Boolean): List<TestObject>{
    return filterTo(ArrayList()){predicate(getValue(it))}.ifEmpty { filterTo(ArrayList(), { getValue(it).isEmpty() })}
    }
and use like this
Copy code
test.emptyFilterIfNotContained({it.a},{it.contains('a')})
💯 1
x
thats incredible
thank you
m
Why do you use
filterTo?