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

Time:06-02

In the reference doc for Scala 3 on extension methods, it gives four ways that extension methods can be looked up. For the forth one, it says:

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.

It gives an example:

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

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

object List:
  ...

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

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

What is the motivation for providing this forth way of looking up extension methods? Is it just for convenience, or does this allow functionality not otherwise possible?

CodePudding user response:

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

That would mean requiring to define the extension for each instance over and over again; although that is still the case in the provided example.

A better example would be this:

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")

The as extension method would be available out of the box.


Although, I personally think most libraries will continue to provide the extensions on a different syntax object to be imported.

  • Related