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.

Rich Oliver
  • 6,001
  • 4
  • 34
  • 57
  • It seems like the static types of both `topComponent` and `bottomComponent` will be `CanvNode`, since you can't tell at compile time what the value of the match expression produces. Can you give a little more information about what you're trying to accomplish? – Connor Doyle Aug 22 '12 at 00:57
  • @ConnorDoyle Edited for clarity – Rich Oliver Aug 22 '12 at 01:04

2 Answers2

6

fold will in fact do what you want here. You can rewrite this:

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

As this:

topComponent = s1.fold(identity, identity)

And the inferred type will be the least upper bound of CSplit and MapCanvT.

Either also provides a slightly more compact way to write this:

topComponent = s1.merge

Through an implicit conversion to a MergeableEither.

Travis Brown
  • 138,631
  • 12
  • 375
  • 680
0

Why not model this differently as a trait?

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
}
stew
  • 11,276
  • 36
  • 49
  • Because MapCanvT can't inherit from CanvNode as its implementations are defined independently of this class. Possibly it could be made into a type class of CanvNode but I think that would be just as complicated as using scala.Either. – Rich Oliver Aug 23 '12 at 15:32