我有两种型号FooApiFooModel:

class FooApi (var aId) 
class FooModel(var mId)

是一种简化过滤FooModel基于FooApiList列出以下功能的方式:

fun f(fooModelList: List<FooModel>, fooApiList: List<FooApi>) : List<FooModel> {
  return fooModelList.filter { fooApiList.map { it.aId }.contains ( it.mId ) }
}

推荐答案

It looks ok to me. I would only change some minor things (not required though), so that it ends up something like the following:

 fun List<FooModel>.f(fooApiList: List<FooApi>) = filter { m -> fooApiList.any { it.aId == m.mId } }

Some reasons why I did it this way:

  • I think that filtering is always applied on a list of FooModels, right? (that is the reason for the extension function narrowing the type to List<FooModel>)
  • You are not interested in the mapped object of fooApiList, so that is why I used any instead; the nice benefit there also is that now both values that are compared are next to each other
  • 总结一切都很容易,您甚至可以省略方法体(因此可以省略返回类型、返回语句等).

Still, that's nearly the same as you did already... Just a bit less code and a rearrangement... Calling it by the way would look like:

val listA : List<FooModel> = TODO()
val listB : List<FooApi> = TODO()

val containedList = listA.f(listB)

If you require such a construct more often, maybe the following more generic solution is helpful:

fun <T, U> List<T>.intersect(uList: List<U>, filterPredicate : (T, U) -> Boolean) = filter { m -> uList.any { filterPredicate(m, it)} }

Which you can then also use like:

val containedList = listA.intersect(listB) {
    a, b -> a.aId == b.mId
}

Then your f again might even look just like:

fun List<FooModel>.f(fooApiList: List<FooApi>) = intersect(fooApiList) { a, b ->  a.mId == b.aId }

Kotlin相关问答推荐

Kotlin中的增广赋值语句中的难以理解的错误

我可以在kotlin/java.util.scanner中跳过分隔符而不重复吗?

&x是T&q;和&q;(x为?T)!=空(&Q;)?

捕捉异常是Kotlin协程中的反模式吗?

用vararg替换列表的设计弃用警告

在Kotlin lambda的参数中如何指定函数类型?

Kotlin 如何使用其 get 函数在内部检索映射值

如果带注释的成员未被特定块包围,则发出 IDE 警告

Kotlin 中的as Long和.toLong()有什么区别?

具有泛型类型的 Kotlin 密封接口不会为其子类型推断约束

PRDownloader 即使在实现库后也无法工作.未知参考:Android Studio 中的 PRDownloader

这是什么 Kotlin 类型:(String..String?)

如何在 Android 的 Fragment 中使用 setUserVisibleHint

对列表中数字的子集求和

Kotlin - 覆盖方法中的 IllegalArgumentException

runInTransaction 块内的挂起方法

Firebase 权限被拒绝

Kotlin reflect proguard SmallSortedMap

安装 Kotlin-Jupyter:e: java.lang.NoClassDefFoundError: 无法初始化类 org.jetbrains.kotlin.com.intellij.pom.java.LanguageLevel

在android java类中使用Kotlin扩展