Kotlin: bring back the common interface

In Kotlin, I am trying to compile the following:

  • for interface with universal types (printer)
  • and two implementations of this 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: fun getMapper(animalType: AnimalType): Printer

I tried to use <Any>or <*>, but did not succeed. Can anyone help?

(it's easy to see the error by copying the code below at 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)
}
+4
source share
3 answers

I changed your code a bit. Now a function getMapper inlinewith a reified generic type, which makes the call pretty readable in getMapper<Dog>().

reified : reified Kotlin?

private inline fun <reified T> getMapper(): Printer<T> {
    when (T::class) {
        Cat::class -> return CatPrinter() as Printer<T>
        Dog::class -> return DogPrinter() as Printer<T>
    }
    throw IllegalArgumentException()
}

fun main(args: Array<String>) {
    println(getMapper<Dog>().mapToString(Dog()))
    println(getMapper<Cat>().mapToString(Cat()))
}

, . getMapper. , . , , , .

+2

Kotlin , Printer getMapper. Printer<*>, getMapper generic, , -.

0

Printer<*> . , mapToString(Dog()) ( , mapToString(5) - ), : ,

getMapper(AnimalType.CAT).mapToString(Dog())

it will also need to be compiled, since the type of the return value may depend only on the type of the argument, and not on the value, but AnimalType.CATalso on AnimalType.DOGthe same type. There are some languages ​​that allow this, but Kotlin is not one of them.

0
source

Source: https://habr.com/ru/post/1688173/


All Articles