【问题标题】:scalaz - using if within for comprehensionscalaz - 使用 if within 进行理解
【发布时间】:2018-03-14 00:57:05
【问题描述】:

我正在尝试使用 EitherT 实现以下目标:

def op1 : EitherT[Future, String, Int] = ???
def op2 : EitherT[Future, String, Int] = ???

for {
  value1 <- op1
  if value1 > 20
  value2 <- op2
} yield value2

但我收到此错误:could not find implicit value for parameter ...

期望的行为是当 op1 的返回值不符合 if 条件时,返回 EitherT(Future.successful("Failed Validation".left[Int])),我该如何实现?

【问题讨论】:

  • 你的意思是def op1: EitherT[Future, String, Int] = ???

标签: scala concurrency monads scalaz monad-transformers


【解决方案1】:

我假设你的意思是这样的:

def op1: EitherT[Future, String, Int] = ???
def op2: EitherT[Future, String, Int] = ???

for {
  value1 <- op1
  value2 <- if (value1 > 20) {
      op2
    } else {
      EitherT(Future.successful("Failed Validation".left[Int]))
    }
} yield value2

【讨论】:

  • 这当然可行,但我希望能有一些接近于理解可以为集合做的事情,所以 if 语句可以是内联的,如果这有意义的话?
  • @BZapper 至少我无法理解它,因为在for-loops 中直接使用的ifs 不是分支,它们是过滤器。而且EitherT 甚至没有正确的withFilter 方法,因为它没有意义:Either 不能简单地“删除”值,只要某些东西不是Right,它需要 Left。但是在withFilter 的签名中,甚至没有任何地方可以在Left 中使用正确的错误消息,它只是返回false,仅此而已。
  • 啊,是的,我跟着。我想接下来最好的事情是一个 handleError 函数,它允许我做类似 onError(_ => EitherT(Future.successful("Failed".left))? 之类的事情?但这并不比 if / else 好多少. 谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 2014-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-09
相关资源
最近更新 更多