在Scala中,我定义了扩展函数,以便可以连接两个Sequence,类似于SQL
implicit def SeqExtensions[X](first: Seq[X]) = new {
def join[Y](second: Y) = new {
def on(predicate: (X, Y) => Boolean) = {
for (ff <- first; if predicate(ff, second)) yield (ff, second)
}
}
}
用法示例:
val joinSeq = unitComponents.flatMap(w => myOtherUnitComponents join w on { (u, w) =>
w.cell equals u.cell
})
=>结果类型为Seq [(UnitComponent,UnitComponent)]
我现在想在Kotlin中编写相同的扩展名(顺序类型并不重要,列表/集合还可以),但是我还不够深刻。有什么提示吗?谢谢。
最佳答案
这将与Scala代码相同:
class IterableJoin<X, Y>(val first: Iterable<X>, val second: Y) {
infix fun on(predicate: (X, Y) -> Boolean) =
first.filter { predicate(it, second) }.map { it to second }
}
infix fun <X, Y> Iterable<X>.join(second: Y) = IterableJoin(this, second)
调用将如下所示:
val joinSeq = unitComponents.flatMap { w ->
myOtherUnitComponents join w on { u, w ->
w.cell == u.cell
}
}
关于kotlin - Join Iterables的扩展功能(Kotlin),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51524772/