如果Kotlin中的参数不为空,则筛选列表
我有以下代码:如果Kotlin中的参数不为空,则筛选列表,kotlin,Kotlin,我有以下代码: list.filterIfNotEmpty(module) { it.name.contains(module!!, ignoreCase = true) } .filterIfNotEmpty(repoUrl) { it.repo.contains(repoUrl!!, ignoreCase = true) } .filterIfNotEmpty(owner) { it.owner.contains(owner!!, ignoreCase = true) }
list.filterIfNotEmpty(module) { it.name.contains(module!!, ignoreCase = true) }
.filterIfNotEmpty(repoUrl) { it.repo.contains(repoUrl!!, ignoreCase = true) }
.filterIfNotEmpty(owner) { it.owner.contains(owner!!, ignoreCase = true) }
fun <T> List<T>.filterIfNotEmpty(value: String?, predicate: (T) -> Boolean): List<T> {
return when {
value.isNullOrBlank() -> this
else -> filterTo(ArrayList<T>(), predicate)
}
}
除非您正在使用的变量是可变的,否则您应该可以使用
这里是code>,因为如果它们的值最初为null,则永远不会调用谓词lambda
您可以通过从谓词中的filterisnofenty
函数获取值来解决这个问题,例如:
fun <T> List<T>.filterIfNotEmpty(value: String?, predicate: (String, T) -> Boolean): List<T> {
return when {
value == null || value.isBlank() -> this
else -> filter { predicate(value, it) }
}
}
fun <T> List<T>.filterIfNotEmpty(value: String?, predicate: (String, T) -> Boolean): List<T> {
return when {
value == null || value.isBlank() -> this
else -> filter { predicate(value, it) }
}
}
list.filterIfNotEmpty(module) { value, element -> element.name.contains(value, ignoreCase = true) }