1

I am looking for way to handle a list of objects in a "polymorphic" way in the manner that you can for a single object. Just to recap what does work:

interface Animal{
   fun sayHello(): String
}
class Dog: Animal{
   override fun sayHello() = "Hello, I'm a dog"
}
class Cat: Animal{
   override fun sayHello() = "Hello, I'm a cat
}

fun printGreeting(animal: Animal){
   println(animal.sayHello())
}

Then of course I can do the following:

val cat = Cat()
val dog = Dog()
printGreeting(cat) // "Hello, I'm a cat"
printGreeting(dog) // "Hello, I'm a dog"

Now imagine I have a List<Animal> and want to handle that in a similar way. I know the following won't work:

fun List<Cat>.sayHello() = "Hello, we are a herd of cats"
fun List<Dog>.sayHello() = "Hello, we are a pack of dogs"

fun printGreeting(animals: List<Animal>){
    println(animals.sayHello())
}

I understand that, due to JVM type erasure, the compiler won't even allow you to declare the above extension functions, since after the erasure it amounts to a redeclaration of the same function.

I am looking for a design pattern that allows me to get the the desired behavior. Any ideas?

2
  • Sealed interface + foreach + when (exhaustive) Oct 15, 2021 at 12:42
  • 2
    A List<Animal> could contain a mixture of Cats and Dogs. I don't think there's a way you can restrict your function to enforce a list of exclusively cats or dogs, so there's no way to create a printGreeting() function the way you've described it. Maybe if you define some default greeting for when there's a mix of animals. You can create those extension functions by annotating them with different @JvmNames.
    – Tenfour04
    Oct 15, 2021 at 13:01

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.