Scala 两者择其一
我想在Scala中使用Scala 两者择其一,scala,Scala,我想在Scala中使用alternative和或[A,B] 以下是我的想法: scala> val x: Either[String, Int] = Left("Foo") x: Either[String,Int] = Left(Foo) scala> val y: Either[String, Int] = Right(5555) y: Either[String,Int] = Right(5555) scala> x.fold(_ => y, _ => x
alternative
和或[A,B]
以下是我的想法:
scala> val x: Either[String, Int] = Left("Foo")
x: Either[String,Int] = Left(Foo)
scala> val y: Either[String, Int] = Right(5555)
y: Either[String,Int] = Right(5555)
scala> x.fold(_ => y, _ => x)
res1: Either[String,Int] = Right(5555)
当只使用标准库时,这是惯用的方法吗
我担心的是,我会有相当数量的
折叠,因为我使用了两个以上的。可能需要一些皮条客:
implicit class EitherOps[A,B] (x: Either[A,B]) {
def orElse (y: => Either[A,B]) = x.fold(_ => y, _ => x)
}
x orElse y orElse z
请记住,它将丢弃除最后一个之外的所有可能的左
s(就像您的示例代码一样)
(更新:使用Odomontois在评论中建议的pass by name)可能类似于此,它可以接受任意数量的参数[]
arg。仅当所有参数都符合相同的类型配置文件时,才会保留类型信息
def firstRight[A,B](args:Either[A,B]*):Either[A,B] = args match {
case Right(x) +: _ => Right(x)
case Seq(Left(x)) => Left(x)
case _ +: tail => firstRight(tail: _*)
}
我不确定你想补充什么,但是<代码> x.Lead。FalpMax(^=>y)看起来是等价的,不确定它是否满足你。在这样的方法中使用传递名称参数更为习惯,因为<代码> y>代码>值不总是被使用。@ OdOntoTo--你会考虑使用<代码>函数0[[a,b] ]吗?
而不是通过名称传递
?@KevinMeredith这不意味着您必须这样做:x orElse(()=>y)orElse(()=>z)
在我看来,它不需要丢失类型信息。也许,或者[A,B]
会是更实际的结果类型。是的,仔细考虑后我同意。我相应地修改了它。