3

Both CSplit and MapCanvT are subtypes of Scala Swing Component. So type CanvNode is always a subtype of Component. I haven't got to grips with the functional stuff of Scala collections yet like fold. Is there any way to reduce this code (aside from putting the match in a function) and get rid of those matches?

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}

The above compiles. Ideally I'd just write:

type CanvNode = Either[CSplit, MapCanvT]   

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

but that won't compile.

4

2 に答える 2

6

fold実際、ここであなたが望むことをします。これを次のように書き換えることができます。

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

このように:

topComponent = s1.fold(identity, identity)

そして、推論された型は と の最小上限にCSplitなりMapCanvTます。

Eitherこれを書くためのもう少しコンパクトな方法も提供します:

topComponent = s1.merge

への暗黙的な変換を通じてMergeableEither.

于 2012-08-22T01:04:43.910 に答える
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
}
于 2012-08-22T10:44:58.517 に答える