[英]Converting Either[L, R] to a value of a common supertype of L and R
If I have a value of type Either[A, B]
, where A extends T
and B extends T
, how can I most easily get a value of type T
? 如果我有Either[A, B]
类型的值,其中A extends T
而B extends T
,我怎样才能最容易得到类型T
的值? Anything more elegant than pattern matching? 还有什么比模式匹配更优雅?
Use merge
: 使用merge
:
val e: Either[A, B] = ???
val result: T = e.merge
You can use fold
with the identity function on both sides - will the one that exists: 您可以在双方使用具有身份功能的fold
- 将存在的那个:
val e: Either[A, B] = ???
val result: T = e.fold(identity[T], identity[T])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.