I need a Collection in Kotlin to contain only elements implementing a given interface.
For example: a Map containing Collection of Animals:
interface Animal { val name: String }
data class Monkey(override val name: String): Animal
data class Snake(override val name: String): Animal
From reading the documentation and blogs and SO questions, I wrote this code that uses the Generics in keyword:
class Test {
private val data = HashMap<String, ArrayList<in Animal>>()
init {
data.put("Monkeys", arrayListOf(Monkey("Kong"), Monkey("Cheetah")))
data.put("Snakes", arrayListOf(Snake("Monthy"), Snake("Kaa")))
}
}
Now I want to add a method in the Test class that reads the content of 'data', for example to print it to the console:
fun printAll() {
data.forEach { collectionName: String, animals: ArrayList<in Animal> ->
println(collectionName)
animals.forEach { animal: Animal ->
println("\t$animal")
}
}
}
If I do that, I have a compilation error:
Error:(27, 21) Kotlin: Type inference failed: Cannot infer type parameter T in inline fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit
None of the following substitutions
receiver: Iterable<Any?> arguments: ((Any?) -> Unit)
receiver: Iterable<Animal> arguments: ((Animal) -> Unit)
can be applied to
receiver: kotlin.collections.ArrayList<in Animal> /* = java.util.ArrayList<in Animal> */ arguments: ((Animal) -> Unit)
My solution is to force my animal to a an ArrayList<out Animal>:
...
(animals as ArrayList<out Animal>).forEach { animal: Animal ->
println("\t$animal")
}
...
But I'm not sure that this is the best way to write this kind of code. Is there a better way to tell Kotlin that I want to use sub types in generics for both producers and consumers ?