List[EitherT[Future, String, CustomObj]] => EitherT[Future, String, List[CustomObj]]

List[EitherT[Future, String, CustomObj]] => EitherT[Future, String, List[CustomObj]]

如何使用 List[EitherT[Future, String, CustomObj]] 的 sequence 函数和自定义 class 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[A] 是什么意思?

这是编辑版,代码@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)))

最初我写道:

Notice please that it didn't compile and produced odd compile messages until I added import scala.concurrent.ExecutionContext.Implicits.global

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