如何在Scala Cats中无需类型别名实现Either的sequence操作
sequence on Either List Without Type Aliases in Cats Hey there, let's break down why your sequence call is throwing that type error and how to fix it without relying on a type alias!
The Root Cause
Scala's type inference can struggle with binary type constructors like Either[A, B] when working with higher-kinded functions like sequence. The sequence method expects a structure of type F[G[A]] (here, F is List, G needs to be a unary type constructor like Either[String, *]—a kind of * -> *).
When you define each element as Right(3):Either[String,Int], Scala sees each element as the concrete type Either[String, Int] (a kind of *), not as the higher-kinded Either[String, ?] that sequence needs to find the Applicative instance for. The type alias XorStr[X] = Either[String,X] fixes this because it explicitly wraps Either into a unary constructor, making type inference work smoothly.
Solutions Without Type Aliases
1. Explicitly Define the List's Element Type
Tell Scala upfront that your list is of type List[Either[String, Int]]—this lets it infer the correct higher-kinded G for sequence:
import cats._, cats.data._, cats.implicits._ // Explicitly type the entire list val les: List[Either[String, Int]] = List(Right(3), Right(2)) les.sequence // Now works! Returns: Either[String, List[Int]] = Right(List(3, 2))
2. Explicitly Specify sequence's Type Parameters
If you prefer not to type the list directly, you can pass the type parameters to sequence to clarify the higher-kinded constructor:
import cats._, cats.data._, cats.implicits._ val les = List(Right(3):Either[String,Int], Right(2):Either[String,Int]) // Use kind projector syntax to specify G as Either[String, *] les.sequence[Either[String, *], Int]
Note: For Scala 2, you'll need the Kind Projector compiler plugin to use the * syntax. If you don't have it, replace Either[String, *] with Either[String, ?].
About Implicit Imports
You didn't miss any critical imports! The cats.implicits._ import already includes the Applicative instance for Either[E, *] (required for sequence). The issue was purely about type inference, not missing implicit values.
内容的提问来源于stack exchange,提问作者Karl

