为什么 Scala 3 支持在 givens 中查找扩展方法?

Why does Scala 3 support looking up extension methods in givens?

extension methods 上的 Scala 3 参考文档中,它提供了四种查找扩展方法的方法。对于第四个,它说:

The reference is of the form r.m and the extension method is defined in some given instance in the implicit scope of the type of r.

举个例子:

object List:
  ...
  given [T: Ordering]: Ordering[List[T]] with
    extension (xs: List[T])
      def < (ys: List[T]): Boolean = ...
end List

但是,您似乎可以轻松地在给定的旁边定义扩展名:

object List:
  ...

  extension [T: Ordering](xs: List[T])
    def < (ys: List[T]): Boolean = ...

  given [T: Ordering]: Ordering[List[T]] with
    ...
end List

提供第四种查找扩展方法的动机是什么?仅仅是为了方便,还是允许使用其他方式无法实现的功能?

However, it seems you could just as easily define the extension next to the given:

这意味着需要为每个实例一遍又一遍地定义扩展;尽管在提供的示例中仍然是这种情况。

一个更好的例子是这样的:

trait Functor[F[_]]:
  extension [A](fa: F[A])
    def map[B](f: A => B): F[B]

    final def as[B](b: B): F[A] = fa.map(_ => b)
end Functor

object List:
  given Functor[List] with:
    extension [A](la: List[A])
      override def map[B](f: A => B): List[B] =
        ...
end List

List(1, 2, 3).as("Foo")

as 扩展方法开箱即用。


尽管如此,我个人认为大多数库将继续在要导入的不同 syntax 对象上提供扩展。