【问题标题】:List[EitherT[Future, String, CustomObj]] => EitherT[Future, String, List[CustomObj]]List[EitherT[Future, String, CustomObj]] => EitherT[Future, String, List[CustomObj]]
【发布时间】:2018-11-20 14:49:23
【问题描述】:

如何将sequence 函数用于带有自定义类 CustomObj 的 List[EitherT[Future, String, CustomObj]] ?我想要这样的东西:

import scala.language.postfixOps
import cats.instances.list._
import cats.syntax.traverse._
import cats.data.EitherT
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

case class CustomObj(int: Int)

private val fst: EitherT[Future, String, CustomObj] =
  EitherT.pure[Future, String](CustomObj(1))
private val snd: EitherT[Future, String, CustomObj] =
  EitherT.pure[Future, String](CustomObj(2))

val source: List[EitherT[Future, String, CustomObj]] = fst :: snd :: Nil

val result: EitherT[Future, String, List[CustomObj]] = source.sequence

import scala.concurrent.duration._
val res = scala.concurrent.Await.result(result.value, 1 second)
println(res) // Right(List(CustomObj(1), CustomObj(2)))

每次编译时我都会得到

 error: Cannot prove that EitherT[Future,String,CustomObj] <:< G[A].

什么意思 <: g>

【问题讨论】:

  • “不起作用”是什么意思?
  • 我得到:错误:无法证明cats.data.EitherT[Future, SomeType1, SomeType2] <: g>
  • 您应该创建一个我们可以复制和粘贴的最小示例。如果没有更多信息,我无法调试。
  • scalacOptions += "-Ypartial-unification" 。如果您使用 maven,只需将其添加到 build.sbt 或 pom.xml。这可以解决问题。现在一切正常。感谢您的 cmets。

标签: scala scala-cats either


【解决方案1】:

这是编辑版,代码@https://scastie.scala-lang.org/Yaneeve/Jro89ZHwS3G23Aveanxc5A

import scala.language.postfixOps
import cats.implicits._
import cats.data.EitherT
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

case class CustomObj(int: Int)

private val fst: EitherT[Future, String, CustomObj] =
  EitherT.pure[Future, String](CustomObj(1))
private val snd: EitherT[Future, String, CustomObj] =
  EitherT.pure[Future, String](CustomObj(2))

val source: List[EitherT[Future, String, CustomObj]] = fst :: snd :: Nil

val result: EitherT[Future, String, List[CustomObj]] = source.sequence

import scala.concurrent.duration._
val res = scala.concurrent.Await.result(result.value, 1 second)
println(res) // Right(List(CustomObj(1), CustomObj(2)))

最初我写道:

请注意它没有编译并产生奇怪的编译消息 直到我添加了import scala.concurrent.ExecutionContext.Implicits.global

确实如此,但是你的麻烦不在于那里。当我再次去重现时,我得到了你指定的错误。缺少的是 SBT/scalac 标志:scalacOptions += "-Ypartial-unification"

【讨论】:

  • 非常感谢..但我得到:错误:无法证明cats.data.EitherT[Future, SomeType1, SomeType2] <: g>
  • 什么是SomeType1 SomeType2?他们不在你的问题中
  • 没关系..顺其自然:EitherT[Future, String, CustomObj] 错误是:无法证明cats.data.EitherT[Future, String, CustomObj] <: g>
  • scastie.scala-lang.org/Yaneeve/Jro89ZHwS3G23Aveanxc5A - 我在这里稍微修改了一下,我会相应地修改我的答案
  • 我仍然收到错误:无法证明 EitherT[Future,String,CustomObj] <: g>
猜你喜欢
  • 2018-06-29
  • 2019-08-12
  • 1970-01-01
  • 2015-08-15
  • 1970-01-01
  • 1970-01-01
  • 2019-11-20
  • 2021-12-28
  • 1970-01-01
相关资源
最近更新 更多