2016-07-06 43 views
3

我有一个使用valueObject的模板,它可能是两种风格之一,具体取决于它在我们的应用中的使用位置。因此,我将其导入为以下之一:Scala要么:最简单的方法来获取左右存在的属性

的ValueObject:要么[对象A,对象B]

这两个对象都对他们产生了相同名称的属性,所以我想找回它只是通过调用

valueObject.propertyA

不工作。

这样做最简洁/最好的方法是什么?

+0

执行定义的propertyA通用超/性状两个对象共享?或者他们只是“发生”拥有该共同财产? –

+0

它们延伸了一个共同的特征。然而,共同特征并未在特征上定义 - 第三个孩子不需要特征 - 但如果这能够优雅地解决我的问题,我可以将它包含在那里。 –

+1

也许你可以使用'fold' – jilen

回答

6

假设两个对象具有相同类型的(或超类型/特性),它定义了属性 - 你可以使用merge如果它存在和右否则它返回左侧,用最低的普通型两者:

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

scala> val e1: Either[MyClass, MyClass] = Left(new MyClass) 
e1: Either[MyClass,MyClass] = Left([email protected]) 

scala> val e2: Either[MyClass, MyClass] = Right(new MyClass) 
e2: Either[MyClass,MyClass] = Right([email protected]) 

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

scala> e2.merge.propertyA 
res1: Int = 1 
+0

非常感谢。那就是诀窍。 –

2

使用fold

假设两个对象不共享存放属性/方法的共同父,那么你就不得不求助于fold

scala> case class A(a: Int) 
defined class A 

scala> case class B(a: Int) 
defined class B 

scala> def foldAB(eab: Either[A,B]): Int = eab.fold(_.a,_.a) 
foldAB: (eab: Either[A,B])Int 

scala> foldAB(Left(A(1))) 
res1: Int = 1 

scala> foldAB(Right(B(1))) 
res2: Int = 1 

模式匹配

另一种可能性是使用模式匹配:

scala> def matchAB(eab: Either[A,B]): Int = eab match { case Left(A(i)) => i; case Right(B(i)) => i} 
matchAB: (eab: Either[A,B])Int 

scala> matchAB(Left(A(1))) 
res3: Int = 1 

scala> matchAB(Right(B(1))) 
res4: Int = 1 
相关问题