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
Copy file name to clipboardExpand all lines: docs/docs/reference/contextual/extension-methods.md
+11-9Lines changed: 11 additions & 9 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -94,7 +94,7 @@ given stringOps: {
94
94
}
95
95
96
96
given {
97
-
def (xs: List[T]) second[T]= xs.tail.head
97
+
def[T](xs: List[T]) second = xs.tail.head
98
98
}
99
99
```
100
100
If such given instances are anonymous (as in the second clause), their name is synthesized from the name of the first defined extension method.
@@ -106,8 +106,8 @@ as well as any type parameters of these extension methods into the given instanc
106
106
For instance, here is a given instance with two extension methods.
107
107
```scala
108
108
givenlistOps: {
109
-
def (xs: List[T]) second[T]:T= xs.tail.head
110
-
def (xs: List[T]) third[T]:T= xs.tail.tail.head
109
+
def[T](xs: List[T]) second: T= xs.tail.head
110
+
def[T](xs: List[T]) third: T= xs.tail.tail.head
111
111
}
112
112
```
113
113
The repetition in the parameters can be avoided by hoisting the parameters up into the given instance itself. The following version is a shorthand for the code above.
@@ -151,26 +151,28 @@ to the implementation of right binding operators as normal methods.
151
151
The `StringSeqOps` examples extended a specific instance of a generic type. It is also possible to extend a generic type by adding type parameters to an extension method. Examples:
152
152
153
153
```scala
154
-
def (xs: List[T]) second [T]=
154
+
def[T](xs: List[T]) second =
155
155
xs.tail.head
156
156
157
-
def (xs: List[List[T]]) flattened [T]=
157
+
def[T](xs: List[List[T]]) flattened =
158
158
xs.foldLeft[List[T]](Nil)(_ ++ _)
159
159
160
-
def (x: T) +[T:Numeric](y: T):T=
160
+
def[T:Numeric](x: T) + (y: T):T=
161
161
summon[Numeric[T]].plus(x, y)
162
162
```
163
163
164
-
As usual, type parameters of the extension method follow the defined method name. Nevertheless, such type parameters can already be used in the preceding parameter clause.
165
-
164
+
If an extension method has type parameters, they come immediately after the `def` and are followed by the extended parameter. When calling a generic extension method, any explicitly given type arguments follow the method name. So the `second` method can be instantiated as follows:
165
+
```scala
166
+
List(1, 2, 3).second[Int]
167
+
```
166
168
167
169
### Syntax
168
170
169
171
The required syntax extension just adds one clause for extension methods relative
170
172
to the [current syntax](../../internals/syntax.md).
171
173
```
172
174
DefSig ::= ...
173
-
| ‘(’ DefParam ‘)’ [nl] id [DefTypeParamClause] DefParamClauses
0 commit comments