Scala 具有相同功能但类型不同的多个方法
使用Scala,我有一个由InputNodes和OutputNodes组成的网络,这两个节点都扩展了一个公共特征NetworkNode。但是,我希望在manager类中添加一个节点,该类为不同类型的节点提供单独的私有集合。这是我第一次尝试:Scala 具有相同功能但类型不同的多个方法,scala,Scala,使用Scala,我有一个由InputNodes和OutputNodes组成的网络,这两个节点都扩展了一个公共特征NetworkNode。但是,我希望在manager类中添加一个节点,该类为不同类型的节点提供单独的私有集合。这是我第一次尝试: // Adds a node into the network, depending on type. def addNode(node: InputNode, name: String = "") = { if (!name.isEmpty
// Adds a node into the network, depending on type.
def addNode(node: InputNode, name: String = "") = {
if (!name.isEmpty()) {
node.name = name
}
this.inputNodes += node
}
def addNode(node: OutputNode, name: String = "") = {
if (!name.isEmpty()) {
node.name = name
}
this.outputNodes += node
}
然而,有两个问题
1) 代码本质上是相同的,但我无法将NetworkNode添加到ArrayBuffer[InputNode],因此需要更具体地使用该类型
2) 无法在同一位置使用默认值重载参数
随着代码的增长,我希望在单个addNode函数中完成所有工作,该函数可以使用匹配结构根据新节点的类型选择新节点的附加位置。这将解决这两个问题,但如何解决集合类型问题?例如,以下操作不起作用:
// Adds a node into the network, type NetworkNode is the common parent.
def addNode(node: NetworkNode, name: String = "") = {
if (!name.isEmpty()) {
node.name = name
}
// Say we deduce class based on a field called TYPE.
node.TYPE match {
case "input" => inputNodes += node // node is a NetworkNode, not an InputNode!!!
case "output" => outputNodes += node
case _ => throw new Exception("Type " + node.TYPE + " is not supported!")
}
}
谢谢你的帮助 此匹配为您进行类型转换
// Adds a node into the network, type NetworkNode is the common parent.
def addNode(node: NetworkNode, name: String = "") = {
if (!name.isEmpty()) {
node.name = name
}
node match {
case x : InputNode => inputNodes += x
case x : OutputNode => outputNodes += x
case _ => throw new Exception("Type " + node.TYPE + " is not supported!")
}
}
顺便说一句,在添加到收藏的同时更改名称似乎很奇怪。这一点现在看来很明显,我看到了。。。感谢您的快速回复!我决定将该名称作为可选参数,以使GUI开发更灵活、更少麻烦。节点本身在其构造函数中根据ID为其分配了默认名称。这样,就不需要使用另一行代码来分配自定义名称,也不需要将其作为构造函数参数。这似乎是子类和继承的经典场景。