zkeme
06/03/2020, 5:51 PMval animals: List<Animal> = ....
val animalToChangeColor = animals[0]
val newColor = ....
val newAnimal = when {
animalToChangeColor is Cat -> {
animalToChangeColor.copy(color = newColor)
}
animalToChangeColor is Sheep -> {
animalToChangeColor.copy(color = newColor)
}
animalToChangeColor is Dog -> {
animalToChangeColor.copy(color = rnewColor)
}
}
Imagine Cat
, Sheep
and Dog
are data classes that implement Animal
interface which has color
field.
It seems impossible to "polyphormise" this, but maybe i'm missing some awesome Kotlin feature 😛Chantry Cargill
06/04/2020, 6:03 AManimal is Dog, animal Is Cat, animal is Sheep -> {}
Or if all of the sealed class implementations have a colour, then just add it to the sealed class as a property.zkeme
06/04/2020, 9:32 AMChantry Cargill
06/04/2020, 9:34 AMzkeme
06/04/2020, 9:40 AMfun Animal.copy(color: Color = this.color): Animal {
return when (this) {
is Sheep -> copy(color = color)
is Dog -> copy(color = color)
is Cat -> copy(color = color)
else -> throw RuntimeException("Unknown subclass of class ${Animal::class.java.simpleName}")
}
}
zkeme
06/04/2020, 9:42 AMArnab Datta
06/09/2020, 2:01 PM