Kotlin / kotlin-koans

Kotlin workshop
MIT License
2.6k stars 1.41k forks source link

Generic functions (task 28) problem #15

Closed aplavin closed 9 years ago

aplavin commented 9 years ago

The proposed correct solution states that the partitionTo function signature should look like this:

fun <T, C: MutableCollection<T>> Collection<T>.partitionTo(first: C, second: C, predicate: (T) -> Boolean): Pair<C, C> {

However, this restricts us to having both first and second collections of the same type. Shouldn't different types (e.g. a list and a set) be allowed? And how to implement this?

Before reading the solution I tried this signature:

fun <T, C1: MutableCollection<in T>, C2: MutableCollection<T>> Iterable<T>.partitionTo(c1: C1, c2: C2, predicate: (T) -> Boolean): Pair<C1, C2> {

but it gives a type mismatch error: inferred type kotlin.List<kotlin.String> is not a subtype of kotlin.MutableCollection<kotlin.String> (when this function is used like partitionTo(ArrayList<String>(), ArrayList()) { s -> !s.contains(" ") }).

svtk commented 9 years ago

Your solution seems to work for me: http://kotlin-demo.jetbrains.com/?publicLink=117459745431996130440-123623408 The only problem is that you have to specify type parameter explicitly, but it will be fixed.