Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Either : simplest way to get a property that exists on right and left

Tags:

scala

either

I have a template using a valueObject that might be one of two flavours depending on where it is used in our app. So I am importing it as an Either:

valueObject: Either[ ObjectA, ObjectB ]

Both objects have an identically named property on them so I would like to retrieve it just by calling

valueObject.propertyA

Which doesn't work.

What is the most concise/ best way of doing this?

like image 600
xeno.be Avatar asked Dec 24 '22 04:12

xeno.be


1 Answers

Assuming the two objects have the same type (or a supertype / trait) that defines that property - you can use merge which returns left if it exists and right otherwise, with the lowest common type of both:

scala> class MyClass {
 | def propertyA = 1
 | }
defined class MyClass

scala> val e1: Either[MyClass, MyClass] = Left(new MyClass)
e1: Either[MyClass,MyClass] = Left(MyClass@1e51abf)

scala> val e2: Either[MyClass, MyClass] = Right(new MyClass)
e2: Either[MyClass,MyClass] = Right(MyClass@b4c6d0)

scala> e1.merge.propertyA
res0: Int = 1

scala> e2.merge.propertyA
res1: Int = 1
like image 58
Tzach Zohar Avatar answered Mar 02 '23 00:03

Tzach Zohar