kotlin 如何检测传递给接口的泛型类型?

6yoyoihd  于 2023-05-01  发布在  Kotlin
关注(0)|答案(1)|浏览(163)

我想允许实现接口的类将泛型类型参数传递给方法。但是编译器无法检测类型,下面的代码无法工作。

interface Handler<T> {
    fun execute(): T
    fun process(data: T)
}

class StringHandler : Handler<String> {
    override fun execute(): String {
        //
    }

    override fun process(data: String) {
        //
    }

}

class IntHandler : Handler<Int> {
    override fun execute(): Int {
        //
    }

    override fun process(data: Int) {
        //
    }

}

fun main() {
    val handler by lazy {
        if (true) {
            StringHandler()
        } else {
            IntHandler()
        }
    }

    val data = handler.execute()
    handler.process(data)
}
zpgglvta

zpgglvta1#

试试这个代码:

interface Handler<T> {
    companion object {
        private val intHandler by lazy { IntHandler() }
        private val stringHandler by lazy { StringHandler() }
        fun <T> process(data: T) {
            when (data) {
                is Int -> intHandler.execute(data)
                is String -> stringHandler.execute(data)
            }
        }
    }

    fun execute(data: T)
}

class StringHandler : Handler<String> {
    override fun execute(data: String) {
        // ...
    }
}

class IntHandler : Handler<Int> {
    override fun execute(data: Int) {
        // ...
    }
}

fun main() {
    Handler.process("")
    Handler.process(1)
}

相关问题