首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将an初始化为Right并指定Left的类型?

如何将an初始化为Right并指定Left的类型?
EN

Stack Overflow用户
提问于 2019-06-10 03:54:24
回答 2查看 1.6K关注 0票数 7

我希望将Either初始化为Left,但这需要指定Right端的类型(反之亦然)。

如果我不这样做,那么默认情况下,Right端的类型为Nothing,以便执行以下操作:

List(5, 42, 7).foldLeft(Left("empty")) {
  case (Left(_), i)  => Right(i)
  case (Right(s), i) => Right(s + i)
}
error: type mismatch;
    found   : scala.util.Right[Nothing,Int]
    required: scala.util.Left[String,Nothing]

显然,我不得不冗长地提供Either两端的类型

List(5, 42, 7).foldLeft(Left("empty"): Either[String, Int]) {
  case (Left(_), i)  => Right(i)
  case (Right(s), i) => Right(s + i)
}

以类似的方式,我可以使用Option.empty[Int]None初始化为Option[Int],是否有方法将Left("smthg")初始化为Either[String, Int]

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-06-10 03:54:24

Scala 2.13开始,Left附带了一个Left#withRight方法,该方法允许将Left[A, Nothing]向上转换为Either[A, B]

Left("smthg").withRight[Int]
// Either[String, Int] = Left("smthg")
Left("smthg")
// Left[String, Nothing] = Left("smthg")

Right端和withLeft也是如此

Right(42).withLeft[String]
// Either[String, Int] = Right(42)

这在你的案例中给出了:

List(5, 42, 7).foldLeft(Left("empty").withRight[Int]) {
  case (Left(_),  i) => Right(i)
  case (Right(s), i) => Right(s + i)
}
// Either[String, Int] = Right(54)
票数 15
EN

Stack Overflow用户

发布于 2019-06-10 04:48:00

为了补充泽维尔的答案,cats还提供了创建Either的实用方法,例如,我们可以这样做:

import cats.implicits._

val right = 7.asRight[String] // Either[String, Int]

val left: = "hello cats".asLeft[Int] // Either[String, Int]

如果我们的项目使用的是scala 2.12或更低版本,它可能会很有用。

如果我们不需要整个cats库,当然,我们可以只借用extension functions for either

implicit class EitherIdOps[A](private val obj: A) extends AnyVal {

  /** Wrap a value in `Left`. */
  def asLeft[B]: Either[A, B] = Left(obj)

  /** Wrap a value in `Right`. */
  def asRight[B]: Either[B, A] = Right(obj)

}
票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56517934

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档