这个 Scala 教程让我很困惑;Node
抽象类型似乎不遵循传统的多态规则......
type Node <: NodeIntf // NodeIntf is assignable to Node.
abstract class NodeIntf {
def connectWith(node: Node): Edge
}
class NodeImpl extends NodeIntf {
def connectWith(node: Node): Edge = {
val edge = newEdge(this, node) // NodeImpl (this) is assignable to NodeIntf.
edges = edge :: edges
edge
}
}
protected def newEdge(from: Node, to: Node): Edge
如果Node = NodeIntf
和NodeIntf = NodeImpl
,那我们为什么不能Node = NodeImpl
呢?我问,因为显然上面的代码不会编译 - 为什么必须使用“自类型引用”?(见教程)