【问题标题】:Share generic type with nested class in Kotlin与 Kotlin 中的嵌套类共享泛型类型
【发布时间】:2018-01-18 17:28:11
【问题描述】:

我正在尝试使用通用类型节点做一个简单的 Dijkstra 探路者。 为此,我有我的探路者类和一个嵌套数据类来提供帮助。 看起来像这样

class Dijkstra<T, U: Number >(  val graph: Graph<T, U>,
                                val from: Node<T, U>,
                                val to: Node<T, U>) {

    private var nodesDistances = mutableMapOf<Node<T, U>, DijkstraDistanceHelper<T, U>>()

    init {
        graph.getNodeList().forEach { nodesDistances[it] = DijkstraDistanceHelper<T, U>(it, null, null) }

        val currentNode = from

        while (currentNode != to) {
            currentNode.getNeighborhood()?.forEach {
                if (it.destination != currentNode) {
                    //it.value type is U and properly recognized as such
                    val currentDistance = it.value + (nodesDistances[currentNode]!!.distance ?: 0)

                    if (nodesDistances[it.destination]?.distance == null
                        || nodesDistances[it.destination]!!.distance!! > currentDistance) {
                        //compilator error on the compare too, same reason I assume
                        nodesDistances[it.destination]!!.distance = currentDistance
                        nodesDistances[it.destination]!!.parentNode = currentNode
                    }
                }
            }
        }
    }

    private data class DijkstraDistanceHelper<T, U: Number>(  val node: Node<T, U>,
                                                              var distance: U?,
                                                              var parentNode: Node<T, U>?)
}

从算法上讲这听起来不太好,但困扰我的是它无法编译:编译器无法理解 Dijkstra 的 U 泛型类型与 DijkstraDistanceHelper 相同

是不是走错路了?如何强制 Dijkstra 的泛型类型(T 和 U)与 DijkstraDistanceHelper 相同?

【问题讨论】:

    标签: generics kotlin inner-classes


    【解决方案1】:

    无法添加抽象的Number 实例。如果您查看文档,您将看到没有定义 plus 运算符。这是因为添加数字具有不同的行为,具体取决于它们是否为浮点数及其内部大小。

    您需要提供添加U 实例的方法,例如(U,U) -&gt; U 作为参数,可以在创建过程中提供Int::plus 或其等效项。

    【讨论】:

    • 我知道这一点,但我希望 DijkstraDistanceHelper 使用 Dijkstra 的泛型类型。我不想重新定义它们。这样当 Dijkstra 的 U 是 Int 时,DijkstraDistanceHelper 的 U 也是 Int 并且不能是别的东西
    • 是的,但是语言无法知道UInt,那么Number + Number 应该做什么?
    猜你喜欢
    • 1970-01-01
    • 2016-10-21
    • 2012-02-01
    • 1970-01-01
    • 2020-06-29
    • 1970-01-01
    • 2019-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多