Value withFilter is not a member of Cats IO in for comprehending

Value withFilter is not a member of Cats IO in for comprehension

我写了这段代码,它编译得很好

for {
  list : List[Int] <- Future(List(1, 2, 3))
} yield list.size 

res7: Future[Int] = Future(Success(3))

但如果我将此代码转换为

for {
  list : List[Int] <- IO(List(1, 2, 3))
} yield list.size

我遇到编译时错误

value withFilter is not a member of cats.effect.IO[List[Int]]

如果我删除类型,那么它可以正常编译

for {
  list  <- IO(List(1, 2, 3)) // returns IO[List[Int]]
} yield list.size 
res8: IO[Int] = Map(Delay(<function0>), <function1>, 0)

为什么我不能用IO指定类型?

我启用了部分统一,所以不可能:)

你的 for-comprehension 被脱糖形成,它使用函数 withFilter,因为 IO 没有那个方法,编译失败。

幸运的是,编译器插件 better-monadic-for 解决了这个问题。

只需在 build.sbt 中添加 addCompilerPlugin("com.olegpy" %% "better-monadic-for" % "0.3.0") 就可以了。