I am so confused, I've been searching how kotlin generics work, but I don't get it at all.
Basically, I have BaseAnimalDetail class, which is being used with some classes extending Animal class. At the moment, there are a lot of when in the BaseAnimalDetail class, so my goal is to avoid all those when, just extending BaseAnimalDetail whenever I need, for each class that extends Animal`
open class BaseAnimalDetail<T : Animal?> : LinearLayout{
private var animal: T? = null
fun setAnimal(animal:T){
this.animal = animal
}
private fun play() {
when(animal){
is Horse -> playWithHorse...
is Dog -> playWithDog...
is Cat -> playWithCat...
}
animal?.let { it.play() } //this is not working but animal?.play works fine, WHY?
}
...More code
}
As you can see, when is super ugly, so I would like to make BaseAnimalDetail abstract and implement it like I said.
Code above is just an example, but it would help me to understand how generics work in Kotlin. It's mandatory for me to have the T var in the base class
Furthermore, WHY animal?.let { it.play() } does not compile?