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
+30-3Lines changed: 30 additions & 3 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -80,7 +80,7 @@ So `circle.circumference` translates to `CircleOps.circumference(circle)`, provi
80
80
81
81
### Given Instances for Extension Methods
82
82
83
-
Given instances that define extension methods can also be defined without a `for` clause. E.g.,
83
+
Given instances that define extension methods can also be defined without an `as` clause. E.g.,
84
84
85
85
```scala
86
86
givenStringOps {
@@ -94,8 +94,33 @@ given {
94
94
def (xs: List[T]) second[T] = xs.tail.head
95
95
}
96
96
```
97
-
If such given instances are anonymous (as in the second clause), their name is synthesized from the name
98
-
of the first defined extension method.
97
+
If such given instances are anonymous (as in the second clause), their name is synthesized from the name of the first defined extension method.
98
+
99
+
### Given Instances with Collective Parameters
100
+
101
+
If a given instance has several extension methods one can pull out the left parameter section
102
+
as well as any type parameters of these extension methods into the given instance itself.
103
+
For instance, here is a given instance with two extension methods.
104
+
```scala
105
+
givenListOps {
106
+
def (xs: List[T]) second[T]:T= xs.tail.head
107
+
def (xs: List[T]) third[T]:T= xs.tail.tail.head
108
+
}
109
+
```
110
+
The repetition in the parameters can be avoided by moving the parameters into the given instance itself. The following version is a shorthand for the code above.
111
+
```scala
112
+
givenListOps[T](xs: List[T]) {
113
+
defsecond:T= xs.tail.head
114
+
defthird:T= xs.tail.tail.head
115
+
}
116
+
```
117
+
This syntax just adds convenience at the definition site. Applications of such extension methods are exactly the same as if their parameters were repeated in each extension method.
118
+
Examples:
119
+
```scala
120
+
valxs=List(1, 2, 3)
121
+
xs.second[Int]
122
+
ListOps.third[T](xs)
123
+
```
99
124
100
125
### Operators
101
126
@@ -143,4 +168,6 @@ to the [current syntax](../../internals/syntax.md).
143
168
```
144
169
DefSig ::= ...
145
170
| ‘(’ DefParam ‘)’ [nl] id [DefTypeParamClause] DefParamClauses
0 commit comments