【发布时间】: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