我很难将通用 Java 代码重构为 Kotlin,因为它更严格。在我遇到的情况下,我不知道该怎么办。
首先,我有interface TopicController
抽象订阅方法,其中一些包含参数type: Class<T>
。在这里,<T>
应该实现类Message
。( <T: Message>
)
我也有一个 TopicController 的实现,即TopicControllerImpl
. 这个类有一个节点列表:val nodes: MutableList<TopicNode<T>>
. 同样在这种情况下T
应该实现Message
.
要做到这一点,我试图将实现定义追加到像类:TopicControllerImpl<T : Message>
。但是,in 中的函数TopicController
也需要有这个实现符号并且它不能从TopicControllerImpl
.
定义它反之亦然,因此有interface TopicController<T : Message>
力量我定义Message
的TopicController
,因此:class TopicControllerImpl(args) : TopicController<*One type argument expected for interface TopicController<T : Message>*>
。
所以要明确:以下代码无法成功编译:
主题控制器实现
class TopicControllerImpl<T: Message>/** ?? */(*[args]*) : TopicController {
private val nodes: MutableList<TopicNode<T>>
override fun subscribe(topic: String, type: Class<T>, subscriber: Messenger) {
val node = findOrCreateNode(topic, type)
node.addListener(subscriber)
}
private fun findOrCreateNode(topic: String, type: Class<T>): TopicNode<T> {
var node = findNode<T>(topic)
if (node != null) {
return node
}
// If node doesn't exist yet, create it, run it and add it to the collection
node = TopicNode(topic, type)
executor.execute(node, configuration)
nodes.add(node)
return node
}
// other functions...
}
主题控制器
interface TopicController<T : Message>{ /** ?? */
fun subscribe(topic: String, type: Class<T>, subscriber: Messenger)
// Other methods
}
所以我想知道如何修复它以便它成功编译......希望我有点清楚,如果你有问题请询问更多细节。
根据kotlin 中的类型推断,如果您的父级使用通配符类型作为类表示,则在子级中从它们继承时需要提供它(在 Java 中也是如此)。
在这种情况下,您TopicController
的类型为T
具有Message
反射的类型。
因此,当您从它继承(或扩展)它的含义时,在子类或接口上实现时,您必须明确提供它。
看看下面的例子:
interface Parent<T : SomeClass> { // Parent can be an abstract class too
// Some methods
}
然后一旦我们在任何孩子身上实施它,
class Child<T: SomeClass> : Parent<T> // We'll need to define T here for parent as it's unknown while inheriting
{
// Some overridden methods
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句