You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The type "implemented" by this given instance is `AnyRef`, which
163
+
is not a type one can summon by itself. This means that the instance can
164
+
only be used for its extension methods.
165
+
166
+
### Collective Extensions
167
+
168
+
Sometimes, one wants to define several extension methods that share the same
169
+
left-hand parameter type. In this case one can "pull out" the common parameters
170
+
into the extension instance itself. Examples:
171
+
```scala
172
+
extension stringOps on (ss: Seq[String]) {
173
+
deflongestStrings:Seq[String] = {
174
+
valmaxLength= ss.map(_.length).max
175
+
ss.filter(_.length == maxLength)
176
+
}
177
+
deflongestString:String= longestStrings.head
138
178
}
139
179
140
180
extension listOps on [T](xs: List[T]) {
141
-
defsecond= xs.tail.head
142
-
defthird:T= xs.tail.tail.head
181
+
defsecond:T= xs.tail.head
182
+
defthird:T= xs.tail.second
143
183
}
144
184
145
185
extension on [T](xs: List[T])(usingOrdering[T]) {
146
186
deflargest(n: Int) = xs.sorted.takeRight(n)
147
187
}
148
188
```
149
-
If an extension is anonymous (as in the last clause), its name is synthesized from the name of the first defined extension method.
150
-
151
-
The extensions above are equivalent to the following regular given instances where the implemented parent is `AnyRef` and the leading parameters are repeated in each extension method definition:
189
+
Collective extensions like these are a shorthand for extension instances where
190
+
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:
Here are the syntax changes for extension methods and collective extensions relative
172
-
to the [current syntax](../../internals/syntax.md). `extension` is a soft keyword, recognized only in tandem with `on`. It can be used as an identifier everywhere else.
173
-
230
+
to the [current syntax](../../internals/syntax.md).
0 commit comments