Skip to content

Commit 5749a3c

Browse files
bishaboshaodersky
authored andcommitted
Add note on export of extensions
1 parent e83d59c commit 5749a3c

File tree

1 file changed

+37
-3
lines changed
  • docs/_docs/reference/other-new-features

1 file changed

+37
-3
lines changed

docs/_docs/reference/other-new-features/export.md

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -162,9 +162,11 @@ extension (x: String)
162162
private def moreOps = new StringOps(x)
163163
export moreOps.*
164164
```
165-
In this case the qualifier expression must be an identifier that refers to a unique parameterless extension method in the same extension clause. The export will create
166-
extension methods for all accessible term members
167-
in the result of the qualifier path. For instance, the extension above would be expanded to
165+
In this case the qualifier expression must be an identifier that refers to a unique parameterless extension method in the same extension clause.
166+
167+
An export will then create extension methods for all accessible term members,
168+
matching the selectors, in the result of the qualifier path.
169+
For instance, the extension above would be expanded to
168170
```scala
169171
extension (x: String)
170172
def take(n: Int): String = x.substring(0, n)
@@ -174,6 +176,38 @@ extension (x: String)
174176
def capitalize: String = moreOps.capitalize
175177
```
176178

179+
### A Note on Exporting Extension Methods
180+
**Note:** extension methods can have surprising results if exported from within an extension (i.e. they
181+
are exported as-if they were an ordinary method). Observe the following example:
182+
```scala
183+
class StringOps:
184+
extension (x: String) def capitalize: String = ...
185+
def zero: String = ""
186+
187+
extension (s: String)
188+
private def moreOps = new StringOps()
189+
export moreOps.*
190+
```
191+
this would be expanded to
192+
```scala
193+
extension (s: String)
194+
private def moreOps = new StringOps()
195+
def capitalize(x: String): String = moreOps.capitalize(x)
196+
...
197+
```
198+
observe the extra String parameter on `capitalize`.
199+
It is instead recommended to export extension methods from
200+
outside of an extension, and to use a renaming selector to avoid them, e.g.:
201+
```scala
202+
private val myStringOps = new StringOps()
203+
204+
extension (s: String)
205+
private def moreOps = myStringOps
206+
export moreOps.{capitalize as _, *}
207+
208+
export myStringOps.capitalize
209+
```
210+
177211
## Syntax changes:
178212

179213
```

0 commit comments

Comments
 (0)