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

克莱纳

我很难将通用 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>力量我定义MessageTopicController,因此: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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

接口与实现接口的类的泛型类型有关?

使用接口作为方法的泛型参数时,如何访问具体接口实现的值

如何使用C#8.0中的nullable选项处理有关泛型的问题?

C#使用泛型和接口实现

通过泛型类使用接口实现

如何处理通用接口实现并避免@SuppressWarnings?

在作为泛型的 binarySearch() 方法中使用关系运算符会出错。如何处理这种情况?

如何在接口实现中使用泛型构造函数?

从 Java 接口实现泛型方法

泛型和接口实现

调用泛型函数(具有通过接口实现的约束)会产生有关缺少约束的错误。我看不到什么?

返回具有不同泛型类型的泛型接口实现

有关Ctypes(以及潜在的python实现)如何处理数据类型的问题?

如何使用MVP模式处理不同的接口实现?

在这种情况下使用什么模式(接口实现)

如何处理这种情况

征求有关如何处理申请的建议

如何处理xarray中与时间有关的坐标?

如何在Kotlin中没有泛型接口的情况下继承实现中的泛型类型?

Java泛型中的接口实现传播

无法为接口实现者创建泛型

通过泛型和接口实现合成

TypeScript 泛型:任何接口实现者

从打字稿接口实现泛型方法

如何正确使用泛型在这种情况下?

如何使用Java泛型解决这种情况?

获取Java泛型的类以及泛型的接口实现

如何实现具有泛型类型的接口?

如何多次实现相同的接口,但使用不同的泛型?