Hi, trying to dynamically choose among implementat...
# announcements
a
Hi, trying to dynamically choose among implementations of an interface, then call a function. For example interface Animal, choose among Cat(), Dog(). My function:
fun makeAnimalSpeak(animalId : Int) : String {
val animalClass : KFunction<Animal> = if (animalId == 1) ::Cat else ::Dog
return animalClass.call().speak() // "meow" or "ruff ruff"
}
Is this reflection? Docs say: Warning: using reflection is usually the wrong way to solve problems in Kotlin! Is the call() method sub-optimal? My app will be calling many functions on the interface, so if there is a more performant way, I'd prefer that. Thanks!
d
Copy code
fun makeAnimalSpeak(animalId : Int) : String {
  val animalClass: () -> CasinoProvider = if (animalId == 1) ::Cat else ::Dog
  return animalClass().speak() // "meow" or "ruff ruff"
}
Should work for you.
It works without reflection. (Haven't tried compiling it).
a
thanks! your solution works without reflection? or mine does?
d
Dominic's solution does not use reflection. Yours does.
a
great, thx very much for the help @diesieben07 @Dominaezzz new solution is working in my code.
m
But I'd ask why you want this code at all when your could has an
animal: Animal
and it can just call
speak()
directly on the
animal
. It appears you have the classes defined that way already, so why not use polymorphism instead?
☝🏼 1
1
s
I agree with Mike, wouldn’t this be simpler?
Copy code
val animal = if (animalId == 1) Cat() else Dog()
return animal.speak()
m
Honestly, I'm unclear as to the objective here. It seems that
makeAnimalSpeak
is a factory AND a processor of an Animal. So additional context might be helpful. Why is
1
a Cat? and everything else is a Dog? I assume this is all 'made up' code, but not sure...
a
@Mike Yes this is made-up code.
Animal
is an interface. My code will have over 40 possible classes implementing the
Animal
interface. Which one to use, won't be known until runtime, and will vary of course. The objective is to find the most efficient coding pattern to call the method (known) on the right class (unknown).
m
Then that's Definitely polymorphism. Use Animal interface in your functions. Construct concrete class when you know. Call 'speak' on interface and the correct function will be called. This is a core feature of OOP as implemented in Java/Kotlin and other languages.
2