Scala:尝试了一种扩展方法,但无法完全构建(多个类上的相同扩展名)

Scala: An extension method was tried, but could not be fully constructed (same extension name on multiple classes)

在 Scala 中,我试图在两个不同的 classes 上定义一个扩展方法。我希望扩展方法具有相同的名称,对于两个 classes.

请注意,classes 与继承无关。

举个例子,假设我有两个 case classes AB,每个都有一个 String 属性,我想定义classes 上的 lower 方法,这将 return 它们的 属性:

的小写
import SomeObject.AExt.lower
import SomeObject.BExt.lower

object SomeObject {

  case class A(foo: String)

  case class B(bar: String)

  object AExt {
    extension (x: A) def lower = x.foo.toLowerCase
  }

  object BExt {
    extension (x: B) def lower = x.bar.toLowerCase
  }

  def hello(): Unit = {
    def a = A("foo")

    def b = B("bar")

    println(a.lower)
    println(b.lower)
  }
}

编译失败并出现此错误:

An extension method was tried, but could not be fully constructed:

    SomeObject.BExt.lower(a)    failed with

        Found:    SomeObject.A
        Required: SomeObject.B

看起来编译器很困惑,正在尝试将 class B 上定义的 lower 扩展应用于我的 A.[=21 实例=]

一种解决方法是将扩展方法放在同一个对象中:

import SomeObject.ABExt.lower
object SomeObject {

  case class A(foo: String)

  case class B(bar: String)

  object ABExt {
    extension (x: A) def lower = x.foo.toLowerCase
    extension (x: B) def lower = x.bar.toLowerCase
  }

  def hello(): Unit = {
    def a = A("foo")

    def b = B("bar")

    println(a.lower)
    println(b.lower)
  }
}