我有一个有很多行的函数。在那个函数中我有一个.filter{}类似的:
fun getMyListForFoo(): List<Blub> {
//.. lot of lines
return myRepo.queryList()
.filter{ it.flag == Query.IS_FOO }
.map{
//..mappings
}
}
Run Code Online (Sandbox Code Playgroud)
然后我有第二个函数只是为了检索不是的查询Foo:
fun getMyListForNotFoo(): List<Blub> {
//.. lot of lines
return myRepo.queryList()
.filter{ it.flag != Query.IS_FOO }
.map{
//..mappings
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所见,唯一的区别是函数中的==or运算符。虽然我已经复制了所有前面的行..!=.filter
我打赌有一个很好的 Kotlin 方法来增强这段代码?
将谓词作为参数传递给函数以过滤列表。
fun getMyList(predicate: (YourType) -> Boolean): List<Blub> {
//.. lot of lines
return myRepo.queryList()
.filter(predicate)
.map{
//..mappings
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
val listForFoo = getMyList { it.flag == Query.IS_FOO }
val listForNotFoo = getMyList { it.flag != Query.IS_FOO }
Run Code Online (Sandbox Code Playgroud)
或者,如果您只想传递布尔值,也可以这样做:
fun getMyList(filterFoo: Boolean): List<Blub> {
//.. lot of lines
return myRepo.queryList()
.filter {
val isFoo = it.flag == Query.IS_FOO
if(filterFoo) isFoo else !isFoo
}
.map{
//..mappings
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
853 次 |
| 最近记录: |