Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* Method extension code
*/
fun <T1, T2> Collection<T1>.combine(other: Iterable<T2>): List<Pair<T1, T2>> {
return combine(other, {thisItem: T1, otherItem: T2 -> Pair(thisItem, otherItem) })
}
fun <T1, T2, R> Collection<T1>.combine(other: Iterable<T2>, transformer: (thisItem: T1, otherItem:T2) -> R): List<R> {
return this.flatMap { thisItem -> other.map { otherItem -> transformer(thisItem, otherItem) }}
}
/**
* Test code
*/
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.spek.api.Spek
class ListCombineSpec : Spek({
describe("list.combine") {
val first = listOf("Kotlin", "Groovy")
val second = setOf("rocks", "kicks-ass", "is awesome")
it("should return a list of Pair objects containing all combinations") {
val combinations = first.combine(second)
assertThat(combinations).containsOnly(
Pair("Kotlin", "rocks"),
Pair("Kotlin", "kicks-ass"),
Pair("Kotlin", "is awesome"),
Pair("Groovy", "rocks"),
Pair("Groovy", "kicks-ass"),
Pair("Groovy", "is awesome")
)
}
it("should return a list of strings that represent the joint strings of all combinations") {
val combinations = first.combine(second, {first, second -> "$first $second"})
assertThat(combinations).containsOnly(
"Kotlin rocks",
"Kotlin kicks-ass",
"Kotlin is awesome",
"Groovy rocks",
"Groovy kicks-ass",
"Groovy is awesome"
)
}
}
})
@finki001

This comment has been minimized.

Copy link

finki001 commented Mar 31, 2017

nice

@CyxouD

This comment has been minimized.

Copy link

CyxouD commented Apr 8, 2017

ty

@kiotaku

This comment has been minimized.

Copy link

kiotaku commented Sep 10, 2017

nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.