[英]Union generic type without Either Scala
This works fine:这工作正常:
def echo[A, B](a: A, b: B): A = ???
This is also fine:这也很好:
def echo[A, B](a: A, b: B): B = ???
However, how do we achieve this to return either type A or B?但是,我们如何实现这一点以返回类型 A 或 B?
// error def echo[A, B](a: A, b: B): A|B =???
Is it simply possible to have a union type of generic types A and B ?是否有可能拥有泛型类型A和B的联合类型? Cheers.干杯。
UPDATE1更新1
Either
is an option but not ideal, as it requires a pattern match when processing the returned result. Either
是一个选项,但并不理想,因为它在处理返回的结果时需要模式匹配。 Effectively, I want this: A <: A|B
, B <: A|B
, which Either
does not achieve.实际上,我想要这个: A <: A|B
, B <: A|B
,这Either
没有实现。
Another extreme, I can do this, but type is too loose:另一个极端,我可以这样做,但是类型太松了:
def echo[A, B](a: A, b: B): Any = ???
UPDATE2更新2
Why I don't want Either
?为什么我不想要Either
?
(Reason 2) (原因 2)
The returned result would actually be a Dataset
of Spark , which requires Encoder
for any type that is not a subtype of Product
(see this topic ).返回的结果实际上是Spark的Dataset
,它需要Encoder
用于任何不是Product
子类型的类型(请参阅本主题)。
When calling this method many times, it ends up with too many Either
wrapping each other, eg Either[Either[Either[...]]]
.多次调用此方法时,最终会导致太多的Either
相互包装,例如Either[Either[Either[...]]]
。 This requires too many encoders to be defined.这需要定义太多的编码器。
So I'm actually doing this:所以我实际上是这样做的:
def echo[A, B](a: A, b: B): Dataset[A|B] = ???
If I do this it would require to have many different encoders due to Either
type:如果我这样做,由于Either
类型,都需要有许多不同的编码器:
def echo[A, B](a: A, b: B): Dataset[Either[A, B]] = ???
val result1: Either[Cat, Dog] = echo(a: Cat, b: Dog)
val result2: Either[Either[Cat, Dog], Pig] = echo(result1: Either[Cat, Dog], c: Pig)
// we have to define encoders:
implicit encoder1: org.apache.spark.sql.Encoders.kryo[Either[Cat, Dog]]
implicit encoder2: org.apache.spark.sql.Encoders.kryo[Either[Either[Cat, Dog], Pig]]
// if we keep iterating, then too many encoders to define...
Soon-to-be-released Scala 3 has it.即将发布的 Scala 3 有它。
def echo[A, B](a: A, b: B): A|B = ??? //this compiles
As can be seen in this Scastie session .从这个 Scastie session中可以看出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.