gpt4 book ai didi

generics - Kotlin:返回一个通用接口(interface)

转载 作者:行者123 更新时间:2023-12-03 14:36:21 25 4
gpt4 key购买 nike

在 Kotlin 中,我正在尝试编译以下内容:

  • 给定一个具有泛型类型的接口(interface)(打印机)
  • 和该接口(interface)的两个实现(DogPrinter 和 CatPrinter)
  • 根据外部变量(AnimalType)返回其中一台打印机

  • 以下代码无法编译,因为在以下位置需要类型: fun getMapper(animalType: AnimalType): Printer
    我尝试使用 <Any><*> 但没有成功。有人可以帮忙吗?

    (通过将下面的代码复制粘贴到 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)
    }

    最佳答案

    我稍微修改了你的代码。 getMapper函数是inlinereified 通用 现在输入,这使得调用在 getMapper<Dog>() 处非常可读.

    阅读 reified这里:What does the reified keyword in Kotlin really do?

    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功能。真正重要的部分是制作这个 通用 .
    未经检查的类型转换不是很酷,但在这里似乎很安全。

    关于generics - Kotlin:返回一个通用接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46938241/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com