Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: accessing common subtype of Either

Tags:

scala

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.

like image 750
Rich Oliver Avatar asked Dec 01 '25 09:12

Rich Oliver


1 Answers

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.

like image 128
Travis Brown Avatar answered Dec 04 '25 01:12

Travis Brown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!