Skip to content

Commit f802fa4

Browse files
committed
Replace import by direct substitution
Don't postulate a synthetic import when expanding collective extensions. Such an import would not typecheck. Postulate a direct substitution of co-defined method identifiers instead.
1 parent 318e9f6 commit f802fa4

File tree

1 file changed

+16
-22
lines changed

1 file changed

+16
-22
lines changed

docs/docs/reference/contextual/extension-methods.md

Lines changed: 16 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -188,41 +188,35 @@ extension on [T](xs: List[T])(using Ordering[T]) {
188188
```
189189
Collective extensions like these are a shorthand for extension instances where
190190
the parameters following the `on` are repeated for each implemented method.
191-
Furthermore, each method's body starts with a synthesized import that
192-
imports all other names of methods defined in the same extension. This lets
193-
one use co-defined extension methods without the repeated prefix parameter,
194-
as is shown in the body of the `longestString` method above.
195-
196-
For instance, the collective extensions above are equivalent to the following extension instances:
191+
For instance, the collective extensions above expand to the following extension instances:
197192
```scala
198193
extension stringOps {
199194
def (ss: Seq[String]).longestStrings: Seq[String] = {
200-
import ss.{longestStrings, longestString}
201195
val maxLength = ss.map(_.length).max
202196
ss.filter(_.length == maxLength)
203197
}
204-
def (ss: Seq[String]).longestString: String = {
205-
import ss.{longestStrings, longestString}
206-
longestStrings.head
207-
}
198+
def (ss: Seq[String]).longestString: String =
199+
ss.longestStrings.head
208200
}
209201
extension listOps {
210-
def [T](xs: List[T]).second: T = {
211-
import xs.{second, third}
212-
xs.tail.head
213-
}
214-
def [T](xs: List[T]).third: T = {
215-
import xs.{second, third}
216-
xs.tail.second
217-
}
202+
def [T](xs: List[T]).second: T = xs.tail.head
203+
def [T](xs: List[T]).third: T = xs.tail.second
218204
}
219205
extension {
220-
def [T](xs: List[T]).largest(using Ordering[T])(n: Int) = {
221-
import xs.largest
206+
def [T](xs: List[T]).largest(using Ordering[T])(n: Int) =
222207
xs.sorted.takeRight(n)
223-
}
224208
}
225209
```
210+
One special tweak is shown in the `longestString` method of the `stringOps` extension. It's original definition was
211+
```scala
212+
def longestString: String = longestStrings.head
213+
```
214+
This uses `longestStrings` as an implicit extension method call on the joint
215+
parameter `ss`. The usage is made explicit when translating the method:
216+
```scala
217+
def (ss: Seq[String]).longestString: String =
218+
ss.longestStrings.head
219+
```
226220

227221
### Syntax
228222

0 commit comments

Comments
 (0)