|
| 1 | +--- |
| 2 | +layout: doc-page |
| 3 | +title: "Extension Methods" |
| 4 | +--- |
| 5 | + |
| 6 | +Extension methods allow one to add methods to a type after the type is defined. Example: |
| 7 | + |
| 8 | +```scala |
| 9 | +case class Circle(x: Double, y: Double, radius: Double) |
| 10 | + |
| 11 | +def (c: Circle) circumference: Double = c.radius * math.Pi * 2 |
| 12 | +``` |
| 13 | + |
| 14 | +Like regular methods, extension methods can be invoked with infix `.`: |
| 15 | + |
| 16 | +```scala |
| 17 | +val circle = Circle(0, 0, 1) |
| 18 | +circle.circumference |
| 19 | +``` |
| 20 | + |
| 21 | +### Translation of Extension Methods |
| 22 | + |
| 23 | +Extension methods are methods that have a parameter clause in front of the defined |
| 24 | +identifier. They translate to methods where the leading parameter section is moved |
| 25 | +to after the defined identifier. So, the definition of `circumference` above translates |
| 26 | +to the plain method, and can also be invoked as such: |
| 27 | +```scala |
| 28 | +def circumference(c: Circle): Double = c.radius * math.Pi * 2 |
| 29 | + |
| 30 | +assert(circle.circumference == circumference(circle)) |
| 31 | +``` |
| 32 | + |
| 33 | +### Translation of Calls to Extension Methods |
| 34 | + |
| 35 | +When is an extension method applicable? There are two possibilities. |
| 36 | + |
| 37 | + - An extension method is applicable if it is visible under a simple name, by being defined |
| 38 | + or inherited or imported in a scope enclosing the application. |
| 39 | + - An extension method is applicable if it is a member of some given instance at the point of the application. |
| 40 | + |
| 41 | +As an example, consider an extension method `longestStrings` on `Seq[String]` defined in a trait `StringSeqOps`. |
| 42 | + |
| 43 | +```scala |
| 44 | +trait StringSeqOps { |
| 45 | + def (xs: Seq[String]) longestStrings = { |
| 46 | + val maxLength = xs.map(_.length).max |
| 47 | + xs.filter(_.length == maxLength) |
| 48 | + } |
| 49 | +} |
| 50 | +``` |
| 51 | +We can make the extension method available by defining a given `StringSeqOps` instance, like this: |
| 52 | +```scala |
| 53 | +given ops1: StringSeqOps |
| 54 | +``` |
| 55 | +Then |
| 56 | +```scala |
| 57 | +List("here", "is", "a", "list").longestStrings |
| 58 | +``` |
| 59 | +is legal everywhere `ops1` is available. Alternatively, we can define `longestStrings` as a member of a normal object. But then the method has to be brought into scope to be usable as an extension method. |
| 60 | + |
| 61 | +```scala |
| 62 | +object ops2 extends StringSeqOps |
| 63 | +import ops2.longestStrings |
| 64 | +List("here", "is", "a", "list").longestStrings |
| 65 | +``` |
| 66 | +The precise rules for resolving a selection to an extension method are as follows. |
| 67 | + |
| 68 | +Assume a selection `e.m[Ts]` where `m` is not a member of `e`, where the type arguments `[Ts]` are optional, |
| 69 | +and where `T` is the expected type. The following two rewritings are tried in order: |
| 70 | + |
| 71 | + 1. The selection is rewritten to `m[Ts](e)`. |
| 72 | + 2. If the first rewriting does not typecheck with expected type `T`, and there is a given instance `i` |
| 73 | + in either the current scope or in the implicit scope of `T`, and `i` defines an extension |
| 74 | + method named `m`, then selection is expanded to `i.m[Ts](e)`. |
| 75 | + This second rewriting is attempted at the time where the compiler also tries an implicit conversion |
| 76 | + from `T` to a type containing `m`. If there is more than one way of rewriting, an ambiguity error results. |
| 77 | + |
| 78 | +So `circle.circumference` translates to `CircleOps.circumference(circle)`, provided |
| 79 | +`circle` has type `Circle` and `CircleOps` is given (i.e. it is visible at the point of call or it is defined in the companion object of `Circle`). |
| 80 | + |
| 81 | +### Given Instances for Extension Methods |
| 82 | + |
| 83 | +A special syntax allows to define a given instance for one or more extension methods without listing a parent type. |
| 84 | +Examples: |
| 85 | + |
| 86 | +```scala |
| 87 | +given stringOps: (xs: Seq[String]) { |
| 88 | + def longestStrings: Seq[String] = { |
| 89 | + val maxLength = xs.map(_.length).max |
| 90 | + xs.filter(_.length == maxLength) |
| 91 | + } |
| 92 | +} |
| 93 | + |
| 94 | +given [T](xs: List[T]) { |
| 95 | + def second = xs.tail.head |
| 96 | + def third[T]: T = xs.tail.tail.head |
| 97 | +} |
| 98 | +``` |
| 99 | +These given clauses define extension methods `longestStrings`, `second`, and `third`. All extension methods defined in such a given clause |
| 100 | +share the same leading parameters, which follow the `given`. The remainder of the extension methods is written as regular defs inside braces. |
| 101 | + |
| 102 | +If such given instances are anonymous (as in the second clause), their name is synthesized from the name of the first defined extension method. |
| 103 | + |
| 104 | + |
| 105 | +### Operators |
| 106 | + |
| 107 | +The extension method syntax also applies to the definition of operators. |
| 108 | +In each case the definition syntax mirrors the way the operator is applied. |
| 109 | +Examples: |
| 110 | +```scala |
| 111 | +def (x: String) < (y: String) = ... |
| 112 | +def (x: Elem) +: (xs: Seq[Elem]) = ... |
| 113 | + |
| 114 | +"ab" + "c" |
| 115 | +1 +: List(2, 3) |
| 116 | +``` |
| 117 | +The two definitions above translate to |
| 118 | +```scala |
| 119 | +def < (x: String)(y: String) = ... |
| 120 | +def +: (xs: Seq[Elem])(x: Elem) = ... |
| 121 | +``` |
| 122 | +Note that swap of the two parameters `x` and `xs` when translating |
| 123 | +the right-binding operator `+:` to an extension method. This is analogous |
| 124 | +to the implementation of right binding operators as normal methods. |
| 125 | + |
| 126 | +### Generic Extensions |
| 127 | + |
| 128 | +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: |
| 129 | + |
| 130 | +```scala |
| 131 | +def (xs: List[T]) second [T] = |
| 132 | + xs.tail.head |
| 133 | + |
| 134 | +def (xs: List[List[T]]) flattened [T] = |
| 135 | + xs.foldLeft[List[T]](Nil)(_ ++ _) |
| 136 | + |
| 137 | +def (x: T) + [T : Numeric](y: T): T = |
| 138 | + summon[Numeric[T]].plus(x, y) |
| 139 | +``` |
| 140 | + |
| 141 | +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. |
| 142 | + |
| 143 | + |
| 144 | +### Syntax |
| 145 | + |
| 146 | +The required syntax extension just adds one clause for extension methods relative |
| 147 | +to the [current syntax](../../internals/syntax.md). |
| 148 | +``` |
| 149 | +DefSig ::= ... |
| 150 | + | ‘(’ DefParam ‘)’ [nl] id [DefTypeParamClause] DefParamClauses |
| 151 | +GivenDef ::= ... |
| 152 | + [GivenSig ‘:’] [ExtParamClause] ExtMethods |
| 153 | +ExtParamClause ::= [DefTypeParamClause] ‘(’ DefParam ‘)’ {GivenParamClause} |
| 154 | +ExtMethods ::= [nl] ‘{’ ‘def’ DefDef {semi ‘def’ DefDef} ‘}’ |
| 155 | +``` |
0 commit comments