在Kotlin中与嵌套类共享genericstypes

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

class Dijkstra( val graph: Graph, val from: Node, val to: Node) { private var nodesDistances = mutableMapOf<Node, DijkstraDistanceHelper>() init { graph.getNodeList().forEach { nodesDistances[it] = DijkstraDistanceHelper(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( val node: Node, var distance: U?, var parentNode: Node?) } 

这在算法上听起来不太合适,但是我不能理解:编译器不能理解Dijkstra的Ugenerics与DijkstraDistanceHelper

这是错误的方式? 我怎样才能强制Dijkstra的genericstypes(T和U)与DijkstraDistanceHelper相同?

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

您将需要提供添加U实例的方法,如(U,U) -> U作为参数,可以在创建时作为Int::plus或其等价物提供。