You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala sequence函数模式匹配报错:自定义List致类型不匹配求助

Fixing the Conflict Between Custom List and Scala's Built-in List

It sounds like you've hit a classic naming collision issue—your custom List class in the same directory is being picked up by the compiler instead of Scala's standard library List, which is why even the correct answer code is throwing that GADT skolem error. Here are three solid ways to fix this:

1. Explicitly Use Fully-Qualified Names for Scala's List

The most direct fix is to tell the compiler exactly which List you mean by using its full path scala.List (and scala.Nil for the empty list). Update your sequence function like this:

def sequence[A](a: scala.List[Option[A]]): Option[scala.List[A]] = 
  a match {
    case scala.Nil => Some(scala.Nil)
    case h :: t => h.flatMap(hh => sequence(t).map(hh :: _))
  }

This removes all ambiguity—every time you write scala.List, the compiler knows you're referring to the standard library implementation, not your custom one.

2. Import Scala's List and Hide the Custom One

Add an import at the top of your file to bring Scala's List and Nil into scope, and optionally hide your custom List to prevent accidental usage:

// Bring Scala's List and Nil into the current scope
import scala.List
import scala.Nil

// If your custom List is in the same package, hide it to avoid conflicts:
// import your.package.here.{List => _, Nil => _}

def sequence[A](a: List[Option[A]]): Option[List[A]] = 
  a match {
    case Nil => Some(Nil)
    case h :: t => h.flatMap(hh => sequence(t).map(hh :: _))
  }

Just replace your.package.here with the actual package where your custom List lives. If you're in the default package (no package declaration), the hide import might not be necessary, but importing scala.List will still take priority over your local class.

3. Rename Your Custom List (Cleanest Long-Term Fix)

If you can, renaming your custom List class to something unique like MyList or CustomList will eliminate the conflict entirely. This is the best approach for maintainability, as you won't have to remember to qualify or import types every time:

// Rename your custom class to avoid collision
class MyList[A] { /* Your custom List implementation here */ }

// Now your original sequence code works as expected
def sequence[A](a: List[Option[A]]): Option[List[A]] = 
  a match {
    case Nil => Some(Nil)
    case h :: t => h.flatMap(hh => sequence(t).map(hh :: _))
  }

Any of these methods should resolve that constructor mismatch error and let you use Scala's built-in List for your sequence function.

内容的提问来源于stack exchange,提问作者drum

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:26:16