Scala,用于理解和 EitherT
Scala, for comprehensions and EitherT
我的技术栈是
- 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 is not a member of cats.data.EitherT
您正在尝试在 for-comprehension 中进行模式匹配(尽管它看起来只是无辜的类型声明)。但是对于内部的模式匹配,需要一个 for-comprehension 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)
}
}
我的技术栈是
- 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 is not a member of cats.data.EitherT
您正在尝试在 for-comprehension 中进行模式匹配(尽管它看起来只是无辜的类型声明)。但是对于内部的模式匹配,需要一个 for-comprehension 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)
}
}