I want an inline function that filters through a list and returns the original list if there is no match rather than returning null
I have this feature that filters through the list and returns the filtered list or empty
fun List<Obj>?.filterQueryText(queryText : String?) = this?.filter {
queryText.equals(it.objName)
}.orEmpty()
How do I make it so that it will return to the original list if no match is found in the query?
CodePudding user response:
This should do the trick
fun List<Obj>?.filterQueryText(queryText : String?) = this?.filter {
queryText.equals(it.objName)
}?.run {if (isEmpty()) this@filterQueryText else this}.orEmpty()
see it in action here
CodePudding user response:
Generic filter for List<T>
:
fun <T> List<T>?.filterOrOriginal(predicate: (T) -> Boolean) : List<T>? =
this?.filter(predicate).takeUnless { it.isNullOrEmpty() } ?: this
Specific filter for List<Obj>
:
fun List<Obj>?.filterQueryTextOrOriginal(queryText : String?) : List<Obj>? =
this?.filterOrOriginal { queryText == it.objName }