如何处理有关使用泛型的接口实现的这种情况?

问题描述 投票:0回答:1

我很难将通用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>强迫我为Message定义一个TopicController,所以: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...
}

TopicController

interface TopicController<T : Message>{ /** ?? */

     fun subscribe(topic: String, type: Class<T>, subscriber: Messenger)

     // Other methods
}

所以我想知道如何解决它成功编译...希望我有点清楚,如果您有任何疑问,请询问更多细节。

java android generics kotlin interface
1个回答
1
投票

根据kotlin中的类型推断,如果您的父级具有Wildcard类型作为类表示,则在从子级继承它们时需要提供它(在java中也是如此)。

在这种情况下,你的TopicControllerT类型,有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
}
© www.soinside.com 2019 - 2024. All rights reserved.