andyg
01/07/2020, 4:12 AMfun 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!Dominaezzz
01/07/2020, 4:20 AMfun makeAnimalSpeak(animalId : Int) : String {
val animalClass: () -> CasinoProvider = if (animalId == 1) ::Cat else ::Dog
return animalClass().speak() // "meow" or "ruff ruff"
}
Should work for you.Dominaezzz
01/07/2020, 4:22 AMandyg
01/07/2020, 4:27 AMdiesieben07
01/07/2020, 8:34 AMandyg
01/07/2020, 9:55 AMMike
01/07/2020, 12:56 PManimal: 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?StavFX
01/07/2020, 6:50 PMval animal = if (animalId == 1) Cat() else Dog()
return animal.speak()
Mike
01/07/2020, 8:23 PMmakeAnimalSpeak
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...andyg
01/08/2020, 3:38 AMAnimal
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).Mike
01/08/2020, 11:07 AM