【发布时间】:2023-03-25 07:55:01
【问题描述】:
我很难将通用 Java 代码重构为 Kotlin,因为它更严格。我不知道在这种情况下该怎么办。
首先我有interface TopicController 具有抽象订阅方法,其中一些包含参数type: Class<T>。这里,<T> 应该实现类Message。 (<T: Message>)
我还有一个 TopicController 的实现,即TopicControllerImpl。这个类有一个节点列表:val nodes: MutableList<TopicNode<T>>。同样在这种情况下T 应该实现Message。
为了实现这一点,我尝试将实现定义附加到类中,例如:TopicControllerImpl<T : Message>。但是,TopicController 中的函数也需要有这个实现符号,它不能从TopicControllerImpl 派生而来。
反之亦然,所以interface TopicController<T : Message> 迫使我为TopicController 定义Message,所以:class TopicControllerImpl(args) : TopicController<*One type argument expected for interface TopicController<T : Message>*>。
所以要明确一点:以下代码确实没有编译成功:
TopicControllerImpl
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
}
所以我想知道如何修复它以使其成功编译...希望我有点清楚,如果您有任何问题,请询问更多详细信息。
【问题讨论】:
-
把你的类语法改成这个
class TopicControllerImpl<T: Message>/** ?? */(*[args]*) : TopicController<T>
标签: java android generics kotlin interface