stefandekanski
01/28/2021, 12:50 PMfun <T, M : MutableCollection<T>> Collection<T>.partitionTo(left: M, right: M, predicate: (T) -> Boolean): Pair<Collection<T>, Collection<T>> {
forEach {
if (predicate(it)) left += it else right += it
}
return Pair(left, right)
}
so as this:
fun <T, C : Collection<T>, M : MutableCollection<T>> C.partitionTo(left: M, right: M, predicate: (T) -> Boolean): Pair<Collection<T>, Collection<T>> {
forEach {
if (predicate(it)) left += it else right += it
}
return Pair(left, right)
}
This doesn’t compile… why?
fun <T, C : Collection<T>, M : MutableCollection<T>> C.partitionTo(left: M, right: M, predicate: (T) -> Boolean): Pair<C, C> {
forEach {
if (predicate(it)) left += it else right += it
}
return Pair(left, right)
}
when you cast it, then i works then but it’s unsafe cast..
fun <T, C : Collection<T>, M : MutableCollection<T>> C.partitionTo(left: M, right: M, predicate: (T) -> Boolean): Pair<C, C> {
forEach {
if (predicate(it)) left += it else right += it
}
return Pair(left as C, right as C)
}
Why can’t typesystem figure out that M is covariant towards C ?Svyatoslav Kuzmich [JB]
01/28/2021, 1:09 PMfun <M, C> foo(m: M): C = m
doesn’t compile: even though they both have Any?
as an upper bound, they can be different types and cannot be assigned to one another.Youssef Shoaib [MOD]
01/29/2021, 2:26 AM@Suppress("BOUNDS_NOT_ALLOWED_IF_BOUNDED_BY_TYPE_PARAMETER")
fun <T, C : Collection<T>, M> C.partitionTo(left: M, right: M, predicate: (T) -> Boolean): Pair<C, C> where M : MutableCollection<T>, M : C {
forEach {
if (predicate(it)) left += it else right += it
}
return Pair(left, right)
}
Please note that this won't be callable from Java because it doesn't understand that signature, that's why that @Suppress
is neededSvyatoslav Kuzmich [JB]
01/29/2021, 7:06 AM