gpt4 book ai didi

scala - 将 Either[A, B] 转换为 Option[A],其中 Left 变为 Some

转载 作者:行者123 更新时间:2023-12-02 16:50:00 24 4
gpt4 key购买 nike

我想将 Either[A, B] 转换为一个选项,这样如果 EitherLeft 它是 Some[A],如果它是 Right,它就是 None

到目前为止我想出了

either.swap.map(Some(_)).getOrElse(None)

有点啰嗦

either match { 
case Left(value) => Some(value)
case Right(_) => None
}

这很好,但理想情况下,我想知道是否有使用方法而不是显式匹配的更惯用的方法。

最佳答案

将 Luis 的评论转换为我们的答案

either.swap.toOption

例如

val either: Either[String, Int] = Left("Boom")
either.toOption
either.swap.toOption

输出

res0: Option[Int] = None
res1: Option[String] = Some(Boom)

我们注意到 either.toOption 返回 Option[Int]either.swap.toOption 返回 Option[String].

很抱歉复制 Luis 的评论,但在我看来,它非常有用,可以作为答案发布。

关于scala - 将 Either[A, B] 转换为 Option[A],其中 Left 变为 Some,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59159309/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com