【问题标题】:How to deal with this situation concerning an interface implementation using generics?如何处理使用泛型实现接口的这种情况?
【发布时间】: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&lt;T: Message&gt;/** ?? */(*[args]*) : TopicController&lt;T&gt;

标签: java android generics kotlin interface


【解决方案1】:

根据 kotlin 中的 type inference,如果您的 parent 使用 Wildcard type 作为类表示,则当您在 child 中从它们继承时需要提供它(在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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-07
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多