Как отобразить опцию внутри для понимания с помощью EitherT - PullRequest
0 голосов
/ 28 декабря 2018

Здравствуйте, я пытаюсь выполнить для понимания, как

(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))
  }
)

Я не могу получить структуру Corret для

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 Ответ

0 голосов
/ 28 декабря 2018
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 в качестве параметра, и понимание будет выглядеть намного лучше)

Надеюсь, что это поможет

update В случае пустого регистра будет успешными будьте счастливы, возвращая пустую последовательность:

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