robinho
08/25/2017, 1:37 PMopen class Noun(val n: String)
open class City(val c: String) : Noun(c)
open class Cabrobro(val j: String) : City(j)
fun <T> copyData(source: MutableList<T>, destination: MutableList<in T>) {
for (item in source) {
destination.add(item)
}
}
fun main(args: Array<String>) {
val source= mutableListOf(City("c1"), City("c2"), City("c3"))
val destination= mutableListOf<Cabrobro>()
copyData(source, destination)
}
robinho
08/25/2017, 1:38 PMMutableList<Cabrobro>
as destination?bdawg.io
09/17/2017, 11:01 PMCabrobro
instances are also City
, but not all City
instances are Cabrobro
. So there’s not really a way to convert City
into all potential sub types implicitly.
Trying to do the inverse and qualifying a second generic type as a subtype of the first would work instead
fun <T, R : T> copyData(source: List<R>, destination: MutableList<T>) {
for (item in source) {
destination.add(item)
}
// can also be written as just:
// source.map(destination::add)
}
bdawg.io
09/17/2017, 11:05 PMfun <T, R : T> List<R>.copyTo(destination: MutableList<T>): MutableList<T> {
this.map(destination::add)
return destination
}
//inside main
val destination = source.copyTo(mutableListOf<City>())
robinho
09/18/2017, 6:28 AM