In Kotlin, I'm trying to compile the following:
- given an interface with generic types (Printer)
- and two implementations of that interface (DogPrinter and CatPrinter)
- return one of the printers, according to an external variable (AnimalType)
The following code does not compile, because a type is required at: fun getMapper(animalType: AnimalType): Printer
I tried to use <Any> or <*> but got no success. Can someone help?
(easy to see the error by copypasting the code below into https://try.kotlinlang.org)
enum class AnimalType { CAT, DOG } class Dog class Cat interface Printer<in T> { fun mapToString(input: T): String } class DogPrinter : Printer<Dog> { override fun mapToString(input: Dog): String { return "dog" } } class CatPrinter : Printer<Cat> { override fun mapToString(input: Cat): String { return "cat" } } private fun getMapper(animalType: AnimalType): Printer { return when(animalType) { AnimalType.CAT -> CatPrinter() AnimalType.DOG -> DogPrinter() } } fun usage_does_not_compile() { getMapper(AnimalType.DOG) .mapToString(5) }