Skip to content

Commit 38ca9b7

Browse files
committed
Clarify blog post about extension methods
1 parent 1947222 commit 38ca9b7

File tree

1 file changed

+28
-6
lines changed

1 file changed

+28
-6
lines changed

docs/blog/_posts/2019-01-21-12th-dotty-milestone-release.md

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,19 +35,41 @@ This is our 12th scheduled release according to our
3535
### Extension Methods
3636

3737
We are excited to announce that extension methods are now offered through dedicated language support!
38-
Extension methods allow one to add methods to a type after the type is defined and up until now they were encoded through the powerful mechanism of implicits.
39-
Previously, one had to place the desired method in the trait with the receiver object to extend, as part of the parameter list.
40-
The infix-ness of the method was being restored by manually writing the implicit class, resolving `implicitly` that extended object.
41-
42-
Now, in Dotty we can express an extension method by writing the method and prepending its name with the type to be extended.
38+
Extension methods allow one to add methods to a type after the type is defined.
39+
This is done by writing a method with a parameter for the type to be extended
40+
_on the left-hand side_ of the method name:
4341

4442
```scala
4543
case class Circle(x: Double, y: Double, radius: Double)
4644

4745
def (c: Circle) circumference: Double = c.radius * math.Pi * 2
4846
```
4947

50-
Read the [relevant documentation](https://dotty.epfl.ch/docs/reference/other-new-features/extension-methods.html) about generic extension methods, higher-kinded extension methods and more.
48+
Extension methods were previously encoded in a rather roundabout way via the implicit class pattern.
49+
Such encoding required a lot of boilerplate, especially when defining type classes.
50+
In Dotty, this is no longer the case,
51+
and type classes with infix syntax become very straightforward to define!
52+
For example, consider:
53+
54+
```scala
55+
trait Semigroup[T] {
56+
def (x: T) combine (y: T): T
57+
}
58+
implicit val IntSemigroup: Semigroup[Int] = new {
59+
def (x: Int) combine (y: Int): Int = x + y
60+
}
61+
implicit def ListSemigroup[T]: Semigroup[List[T]] = new {
62+
def (x: List[T]) combine (y: List[T]): List[T] = x ::: y
63+
}
64+
1.combine(2) // == 3
65+
List(1,2).combine(List(3,4)) // == List(1,2,3,4)
66+
```
67+
68+
This works because extension methods become available
69+
not only if they are syntactically in scope,
70+
but also if they are present in the relevant implicit scope.
71+
72+
Read the [full documentation](https://dotty.epfl.ch/docs/reference/other-new-features/extension-methods.html) about generic extension methods, higher-kinded extension methods, and more.
5173

5274
### TASTy Reflect goodies
5375

0 commit comments

Comments
 (0)