Scala,用于理解和EitherT

时间:2018-11-01 15:52:48

标签: scala scala-cats

我的技术栈是

  • Play Framework 2.6
  • Scala 2.12.6
  • Play-Slick 3.0.0
  • 猫1.4.0

我正在尝试实现此功能以更新数据库中的行

def update(userId: Long, user: User) = {
  (for {
    _ <- EitherT(updateUser(userId, user))
    user: User <- EitherT(findById(userId))
    userProfile: userProfile <- EitherT(userProfileRepository.findById(user.userProfileId))
  } yield (user, userProfile).map {
    case (user: User, userProfile: UserProfile) =>
      val response = new UserResponse(user, userProfile)
      Right(response)
    case error =>
      val str = s"update failure: $error"
      Left(str)
  }
}

但是当我尝试使用EitherT编译此代码时,我会得到

  

value withFilter不是cats.data.EitherT的成员

1 个答案:

答案 0 :(得分:6)

您正在尝试在理解中进行模式匹配(尽管它看起来只是无辜的类型声明)。但是,对于全面理解withFilter内部的模式匹配是必需的(想想如果模式匹配失败怎么办?)。因此,删除匹配的类型,它应该可以工作:

def update(userId: Long, user: User) = {
  (for {
    _ <- EitherT(updateUser(userId, user))
    user <- EitherT(findById(userId))
    userProfile <- EitherT(userProfileRepository.findById(user.userProfileId))
  } yield (user, userProfile).map {
    case (user: User, userProfile: UserProfile) =>
      val response = new UserResponse(user, userProfile)
      Right(response)
    case error =>
      val str = s"update failure: $error"
      Left(str)
  }
}
相关问题