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
If such given instances are anonymous (as in the second clause), their name is synthesized from the name of the first defined extension method.
101
-
102
-
### Given Instances with Collective Parameters
103
-
104
-
If a given instance has no parent but several extension methods one can pull out the left parameter section
105
-
as well as any type parameters of these extension methods into the given instance itself.
106
-
For instance, here is a given instance with two extension methods.
107
-
```scala
108
-
givenlistOps: {
109
-
def [T](xs: List[T]) second: T= xs.tail.head
110
-
def [T](xs: List[T]) third: T= xs.tail.tail.head
111
-
}
112
-
```
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.
114
-
```scala
115
-
givenlistOps: [T](xs: List[T]) {
116
-
defsecond:T= xs.tail.head
117
-
defthird:T= xs.tail.tail.head
118
-
}
119
-
```
120
-
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.
121
-
Examples:
122
-
```scala
123
-
valxs=List(1, 2, 3)
124
-
xs.second[Int]
125
-
ListOps.third[T](xs)
126
-
```
127
-
128
84
### Operators
129
85
130
86
The extension method syntax also applies to the definition of operators.
@@ -165,6 +121,40 @@ If an extension method has type parameters, they come immediately after the `def
165
121
```scala
166
122
List(1, 2, 3).second[Int]
167
123
```
124
+
### Given Instances for Extension Methods
125
+
126
+
The `given extends` syntax lets on define given instances that define extension methods and nothing else. Examples:
127
+
128
+
```scala
129
+
givenstringOpsextends (xs: Seq[String]) {
130
+
deflongestStrings:Seq[String] = {
131
+
valmaxLength= xs.map(_.length).max
132
+
xs.filter(_.length == maxLength)
133
+
}
134
+
}
135
+
136
+
givenextends [T](xs: List[T]) {
137
+
defsecond= xs.tail.head
138
+
defthird:T= xs.tail.tail.head
139
+
}
140
+
```
141
+
If such given instances are anonymous (as in the second clause), their name is synthesized from the name of the first defined extension method.
142
+
143
+
The extension method definitions above are equivalent to the following standard given instances where
144
+
the implemented parent is `AnyRef` and the parameters after the `extend` clause are repeated in each
0 commit comments