We are considering adding extension methods to Scala 3 in the form they are currently described on the Dotty doc page.
case class Circle(x: Double, y: Double, radius: Double) def (c: Circle) circumference: Double = c.radius * math.Pi * 2
The main novel feature of extension methods is their integration with implicit search:
- An extension method is applicable if it is a member of some implied instance at the point of the application.
This allows a clean notation for type classes, without the need to import decorator classes to get infix operations.
Extension methods are a more straightforward and simpler alternative to implicit classes. The proposed
design integrates well with implicit search, enabling a pleasing and lightweight notation for type classes.
The proposal has already undergone extensive discussions on the PR with 165 comments posted. The discussion focussed mostly on the syntax. In fact, several alternative syntactic forms were implemented and tried out before settling on the one in the current proposal. A popular alternative syntax is to use C# style extension methods with a
this modifier in front of the “left” parameter.
def < (this x: String)(y: String) = ...
instead of the now implemented
def (x: String) < (y: String)
It’s not an easy choice. I was for while convinced that C# style was the way to go, to a point where I did a complete implementation and gave several talks last fall about the new feature with this syntax. But the more I used it and talked about it, the more the syntax felt awkward to me, as something that does not quite fit and that requires too many explanations. One case whether this is particularly blatant are right binding operators. E.g.
def +: (this xs: Iterable[Elem])(x: Elem): Iterable[Elem]
def (x: Elem) +: (xs: Iterable[Elem]): Iterable[Elem]
That’s why I changed in the end to the current syntax.
If people would like to discuss syntax here and maybe propose a new one, it would be good to first consult the comments in the PR to see what was discussed and discarded already.