Skip to content

Commit 77447c8

Browse files
committed
Add note on export of extensions
1 parent fe8a11c commit 77447c8

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
@@ -153,9 +153,11 @@ extension (x: String)
153153
private def moreOps = new StringOps(x)
154154
export moreOps.*
155155
```
156-
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
157-
extension methods for all accessible term members
158-
in the result of the qualifier path. For instance, the extension above would be expanded to
156+
In this case the qualifier expression must be an identifier that refers to a unique parameterless extension method in the same extension clause.
157+
158+
An export will then create extension methods for all accessible term members,
159+
matching the selectors, in the result of the qualifier path.
160+
For instance, the extension above would be expanded to
159161
```scala
160162
extension (x: String)
161163
def take(n: Int): String = x.substring(0, n)
@@ -165,6 +167,38 @@ extension (x: String)
165167
def capitalize: String = moreOps.capitalize
166168
```
167169

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

170204
```

0 commit comments

Comments
 (0)