代码之家  ›  专栏  ›  技术社区  ›  agusgambina

如何用EitherT映射一个选项以供理解

  •  0
  • agusgambina  · 技术社区  · 7 年前

    嗨,我正在尝试执行一个类似于

    (for {
      player <- playerRepository.findById(playerId) // findById returns EitherT[Future, String, Player]
      teamOpt <- teamRepository.findByPlayer(playerId) // findByPlayer returns EitherT[Future, String, Option[Team]]
      playedMatches <- teamOpt.map(team => playedMatchesRepository.findByTeamId(team.id)) // findByTeamId returns EitherT[Future, String, Seq[PlayedMatches]]
    } yield (
      player,
      teamOpt,
      playedMatches
    )).fold(
      error => {
        logger.error(s"all error: $error")
        Left(error)
      },
      tuple => {
        logger.debug(s"get success -> $tuple")
        Right(playerDetailResponse(tuple._1, tuple._2, tuple._3))
      }
    )
    

    playedMatches <- teamOpt.map(team => playedMatchesRepository.findByTeamId(team.id))
    

    当我编译项目时,我得到了以下错误

    [error] /Users/agusgambina/code/soccer/app/services/impl/PlayerServiceImpl.scala:28:17: type mismatch;
    [error]  found   : Option[(models.Player, Option[models.Team], cats.data.EitherT[scala.concurrent.Future,String,Seq[models.PlayedMatches]])]
    [error]  required: cats.data.EitherT[scala.concurrent.Future,?,?]
    [error]       playedMatches <- teamOpt.map(team => playedMatchesRepository.findByTeamId(team.id))
    [error]                 ^
    [error] one error found
    

    1 回复  |  直到 7 年前
        1
  •  1
  •   FerranJr    7 年前
    playedMatches <- teamOpt.map(team => playedMatchesRepository.findByTeamId(team.id)) // findByTeamId returns EitherT[Future, String, Seq[PlayedMatches]]
    

    在这里,您将获得一个选项[EitherT[Future,String,Seq[PlayedMatches]]],该选项不与您用作单子的EitherT[Future,String,?组成,以便于理解。

    您可以选择在teamOpt上实际使用折叠。

    teamOpt.fold(EitherT(Future.successful(Left("Team not Found"): Either[String, Team]))){ team => playedMatchesRepository.findByTeamId(team.id) }
    

    希望能有帮助

    使现代化 如果是空的情况,请成功,并愉快地返回空序列:

    teamOpt.fold(
      EitherT(Future.successful(Right(Seq()): Either[String, Seq[PlayedMatches]))
    ){ team =>
      playedMatchesRepository.findByTeamId(team.id) 
    }
    
    推荐文章