具有不同泛型类型的 Scala 3 扩展重载

Scala 3 extension overloading with different generic types

我正在从 Scala 2.13 迁移到 Scala 3,我正在尝试重写一些小的实用程序函数。在 2.13 中,可以编写一个更通用的隐式和另一个更具体的,但在 Scala 3 中似乎不再可能。

  type Outcome[+E <: Fail, A] = Either[E, A]

  extension[A] (list: List[Outcome[ValidationFail, A]]) {
    def outcomeListAll: Outcome[ValidationFail, List[A]] = {
      val (left, right) = list.partitionOutcome
      if (left.isEmpty) {
        Right(right)
      } else {
        Left(left.reduce(_ + _))
      }
    }
  }

  extension[F <: Fail, A] (list: List[Outcome[F, A]])
    @deprecated
    def outcomeListAll: Outcome[Fail, List[A]] = {
      val (left, right) = partitionOutcome
      if (left.isEmpty) {
        Right(right)
      } else {
        Left(Fail.generic(left.map(_.getMessage).mkString(", "), left.head))
      }
    }
    def partitionOutcome: (List[F], List[A]) = {
      val left: List[F] = list.collect {
        case Left(l) => l
      }
      val right: List[A] = list.collect {
        case Right(r) => r
      }
      (left, right)
    }

当我尝试编译以上代码片段时出现双重定义错误。至少根据 this 文章应该解析为具有不同签名的方法。像这样:

<extension> def < (x: String)(y: String): Boolean = ...
<extension> def +: (xs: Seq[Elem])(x: Elem): Seq[Elem] = ...
<extension> infix def min(x: Number)(y: Number): Number = ...

我知道我可以简单地使用模式匹配,但我不能像使用方法那样重载扩展似乎很奇怪。

编译错误:

[error] -- [E120] Naming Error: /home/...testing/Main.scala:19:8 
[error] 19 |    def outcomeListAll: Outcome[Fail, List[A]] = {
[error]    |        ^
[error]    |Double definition:
[error]    |def outcomeListAll(list: scala.collection.immutable.List): scala.util.Either in object Main at line 7 and
[error]    |def outcomeListAll(list: scala.collection.immutable.List): scala.util.Either in object Main at line 19
[error]    |have the same type after erasure.
[error]    |
[error]    |Consider adding a @targetName annotation to one of the conflicting definitions
[error]    |for disambiguation.

正如所指出的,问题可以通过使用注释@targetName("...")

来解决
  import scala.annotation.targetName

  type Outcome[+E <: Fail, A] = Either[E, A]

  extension[A] (list: List[Outcome[ValidationFail, A]]) {
    @targetName("outcomeListAllForValidationFail")
    def outcomeListAll: Outcome[ValidationFail, List[A]] = {
      val (left, right) = list.partitionOutcome
      if (left.isEmpty) {
        Right(right)
      } else {
        Left(left.reduce(_ + _))
      }
    }
  }

  extension[F <: Fail, A] (list: List[Outcome[F, A]])
    def outcomeListAll: Outcome[Fail, List[A]] = {
      val (left, right) = partitionOutcome
      if (left.isEmpty) {
        Right(right)
      } else {
        Left(Fail.generic(left.map(_.getMessage).mkString(", "), left.head))
      }
    }
    def partitionOutcome: (List[F], List[A]) = {
      val left: List[F] = list.collect {
        case Left(l) => l
      }
      val right: List[A] = list.collect {
        case Right(r) => r
      }
      (left, right)
    }