Scala:访问Either的常见子类型

时间:2012-08-22 00:40:28

标签: scala

CSplit和MapCanvT都是Scala Swing Component的子类型。因此,类型CanvNode始终是Component的子类型。我还没有掌握Scala系列的功能,还有像折叠一样。有没有办法减少这个代码(除了把匹配放在一个函数中)并摆脱那些匹配?

type CanvNode = Either[CSplit, MapCanvT]   

class CSplit(var s1: CanvNode, var s2: CanvNode) extends SplitPane
{         
  topComponent =  s1 match { case Left (s) => s; case Right (s) => s} 
  bottomComponent = s2 match { case Left (s) => s; case Right (s) => s}

以上编译。理想情况下,我只想写:

type CanvNode = Either[CSplit, MapCanvT]   

class CSplit(var s1: CanvNode, var s2: CanvNode) extends SplitPane
{         
  topComponent =  s1
  bottomComponent = s2

但不会编译。

2 个答案:

答案 0 :(得分:6)

fold实际上会在这里做你想做的事。你可以改写这个:

topComponent = s1 match { case Left (s) => s; case Right (s) => s}

这样:

topComponent = s1.fold(identity, identity)

推断类型将是CSplitMapCanvT的最小上限。

Either也提供了一种更为紧凑的方式来写这个:

topComponent = s1.merge

通过隐式转换为MergeableEither

答案 1 :(得分:0)

为什么不将它作为特征进行不同的模拟?

sealed trait CanvNode
class MapCanvT extends Component with CanvNode
class CSplit extends SplitPane with CanvNode(var s1: CanvNode,
                                             var s2: CanvNode) {
    topComponent = s1
    bottomCompoenent = s2
}