【问题标题】:Convert Type1: EitherT[Future, String, Int] to Type2: EitherT[Future, String, Option[Int]] while all the Left in Type1 become Right(None) in Type2将 Type1:EitherT[Future, String, Int] 转换为 Type2:EtherT[Future, String, Option[Int]] 而 Type1 中的所有 Left 在 Type2 中变为 Right(None)
【发布时间】:2020-07-22 11:12:07
【问题描述】:

假设我有一个:

val origin_left: EitherT[Future, String, Int] = EitherT.fromEither[Future](Left("some-error"))
val origin_right: EitherT[Future, String, Int] = EitherT.fromEither[Future](Right(100))

我想把它转换成

val converted_left: EitherT[Future, String, Option[Int]] = EitherT.fromEither[Future](Right(None))
val converted_right: EitherT[Future, String, Option[Int]] = EitherT.fromEither[Future](Right(Some(100)))

我想这样做的原因是,如果你有一个 Left,for 理解将立即结束。所以我想将 Left 转换为 Right(None) 以继续理解。

【问题讨论】:

    标签: scala scala-cats


    【解决方案1】:

    经过一番尝试,我找到了答案(使用折叠):

    val converted = EitherT(origin.fold(_ => Right(None), num => Right(Some(num))))
    

    【讨论】:

      猜你喜欢
      • 2021-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-12
      • 1970-01-01
      • 2015-05-28
      • 2012-01-23
      • 1970-01-01
      相关资源
      最近更新 更多