gpt4 book ai didi

Kotlin 通用接口(interface)解析器

转载 作者:行者123 更新时间:2023-12-02 13:10:56 24 4
gpt4 key购买 nike

我正在尝试构建一个解析器,它给定一些域上下文返回一个通用接口(interface)的实现。代码如下(域抽象):

interface Interface<T>

class StringImplementation: Interface<String>

class BooleanImplementation: Interface<Boolean>

class Resolver {

fun <T : Any> resolve(implementation: String): Interface<T> {
return when (implementation) {
"string" -> StringImplementation()
"boolean" -> BooleanImplementation()
else -> throw IllegalArgumentException()
}
}

}

这个片段对我来说看起来不错,但编译器提示因为 Type missmatch: Required: Interface<T> Found: StringImplementation在第 11 行和 Type missmatch: Required: Interface<T> Found: BooleanImplementation在第 12 行。

为什么这是个问题?我虽然设置 <T : Any>在方法契约(Contract)中将允许返回任何类型的实现。这里的限制是方法的返回类型 resolve必须是 Interface<T> , 将其替换为 Interface<*>会使编译器闭嘴,但这不是我们所需要的。

最佳答案

TL;博士

一个函数只能有 1 种返回类型,但您的函数有 2 种不同的返回类型。

只有这样才能工作:

interface Interface<T>

class StringImplementation: Interface<String>

class BooleanImplementation: Interface<Boolean>

class Resolver {

fun resolve(implementation: String): Interface<*> { // <-- star
return when (implementation) {
"string" -> StringImplementation()
"boolean" -> BooleanImplementation()
else -> throw IllegalArgumentException()
}
}

}

解释

从函数定义的角度来看,它必须有一个明确的、明确的返回类型。 Interface<T>说应该是扩展 Interface显式 类型 T 执行开始可以知 Prop 体的实现的功能。
您的代码中无法知道 T 是什么将在您调用 resolve 时.你怎么能想象这个函数知道它会返回什么?!

缩短:一个函数只能有 1 种返回类型,但您的函数有 2 种不同的返回类型( Interface<String>/ Interface<Boolean> )。

Continue to read here如果您想深入研究泛型并获得更多技术描述。

关于Kotlin 通用接口(interface)解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62425738/

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