在Scala中遍历 [英] Traversing Either in Scala
问题描述
我编写了以下简单代码:
I wrote the following simple code:
import cats.effect.IO
import cats.instances.either._
import cats.syntax.TraverseSyntax
object Test extends App with TraverseSyntax{
val e: Either[String, IO[Int]] = Right(IO(2))
e.sequence //error here
}
不幸的是,它拒绝使用
Error:(25, 94) value sequence is not a member of scala.util.Either
能否请您解释原因?我导入了包含Traverse[Either[A, ?]]
的either
实例.怎么了?
Can you please explain why? I imported either
instances which include Traverse[Either[A, ?]]
. What's wrong?
推荐答案
Traverse[F]
被定义为具有一个类型参数F[T]
的类型的类型类. Either
类型有两个类型参数,因此Scala不能将转换应用于Traverse.Ops
以对类型为Either
定义的对象使用遍历语法方法.
Traverse[F]
is defined as a typeclass for a type with one type parameter F[T]
. Either
type has two type parameters, so Scala can't apply the conversion to Traverse.Ops
to use traverse syntax methods on objects defined with type Either
.
要使其可用,可以为Either
定义类型别名,该别名固定第一个type参数的值,因此只有一个type参数.然后,Scala将能够在使用此类型别名定义的变量上使用遍历语法:
To make them available, you can define a type alias for Either
, that fixes the value of the first type parameter, and thus has only one type parameter. Scala then will be able to use the traverse syntax on the variables defined with this type alias:
type StringOr[T] = Either[String, T]
val e: StringOr[IO[Int]] = Right(IO(2))
e.sequence
另一种方法是使用lambdas类型或投影机编译器插件,然后在其上调用sequence
方法并传递您的值:
Another method is to get an instance of Traverse
for your type, using type lambdas or the kind projector compiler plugin, and then call sequence
method on it passing your value:
val e: Either[String, IO[Int]] = Right(IO(2))
// With type lambda
Traverse[({ type L[T] = Either[String, T] })#L].sequence(e)
// With kind projector
Traverse[Either[String, ?]].sequence(e)
这篇关于在Scala中遍历的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!