|
| 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 | +extension CircleOps for Circle { |
| 12 | + def circumference: Double = this.radius * math.Pi * 2 |
| 13 | +} |
| 14 | +``` |
| 15 | + |
| 16 | +The extension adds a method `circumference` to values of class `Circle`. Like regular methods, extension methods can be invoked with infix `.`: |
| 17 | + |
| 18 | +```scala |
| 19 | + val circle = Circle(0, 0, 1) |
| 20 | + circle.circumference |
| 21 | +``` |
| 22 | + |
| 23 | +### Meaning of `this` |
| 24 | + |
| 25 | +Inside an extension method, the name `this` stands for the receiver on which the |
| 26 | +method is applied when it is invoked. E.g. in the application of `circle.circumference`, |
| 27 | +the `this` in the body of `circumference` refers to `circle`. As usual, `this` can be elided, so we could also have defined `CircleOps` like this: |
| 28 | + |
| 29 | +```scala |
| 30 | +extension CircleOps for Circle { |
| 31 | + def circumference: Double = radius * math.Pi * 2 |
| 32 | +} |
| 33 | +``` |
| 34 | + |
| 35 | +### Scope of Extensions |
| 36 | + |
| 37 | +Extensions can appear anywhere in a program; there is no need to co-define them with the types they extend. Extension methods are available wherever their defining extension is in scope. Extensions can be inherited or imported like normal definitions. |
| 38 | + |
| 39 | +### Extended Types |
| 40 | + |
| 41 | +An extension can add methods to arbitrary types. For instance, the following |
| 42 | +clause adds a `longestStrings` extension method to a `Seq[String]`: |
| 43 | + |
| 44 | +```scala |
| 45 | +extension StringOps for Seq[String] { |
| 46 | + def longestStrings: Seq[String] = { |
| 47 | + val maxLength = map(_.length).max |
| 48 | + filter(_.length == maxLength) |
| 49 | + } |
| 50 | +} |
| 51 | +``` |
| 52 | + |
| 53 | +### Generic Extensions |
| 54 | + |
| 55 | +The previous example extended a specific instance of a generic type. It is also possible |
| 56 | +to extend a generic type by adding type parameters to an extension: |
| 57 | + |
| 58 | +```scala |
| 59 | +extension ListOps[T] for List[T] { |
| 60 | + def second: T = tail.head |
| 61 | +} |
| 62 | +``` |
| 63 | + |
| 64 | +or: |
| 65 | + |
| 66 | + |
| 67 | +```scala |
| 68 | +extension ListListOps[T] for List[List[T]] { |
| 69 | + def flattened: List[T] = foldLeft[List[T]](Nil)(_ ++ _) |
| 70 | +} |
| 71 | +``` |
| 72 | + |
| 73 | +### Bounded Generic Extensions |
| 74 | + |
| 75 | +It is possible to use bounds for the type parameters of an extension. But subtype and context bounds are supported: |
| 76 | + |
| 77 | +```scala |
| 78 | +extension ShapeListOps[T <: Shape] for List[T] { |
| 79 | + def totalArea = map(_.area).sum |
| 80 | +} |
| 81 | + |
| 82 | +extension OrdSeqOps[T : math.Ordering] for Seq[T] { |
| 83 | + def indexOfLargest = zipWithIndex.maxBy(_._1)._2 |
| 84 | + def indexOfSmallest = zipWithIndex.minBy(_._1)._2 |
| 85 | +} |
| 86 | +``` |
| 87 | + |
| 88 | +### Implicit Parameters for Type Patterns |
| 89 | + |
| 90 | +The standard translation of context bounds expands the bound in the last example to an implicit _evidence_ parameter of type `math.Ordering[T]`. It is also possible to give evidence parameters explicitly. The following example is equivalent to the previous one: |
| 91 | + |
| 92 | +```scala |
| 93 | +extension OrdSeqOps[T](implicit ev: math.Ordering[T]) for Seq[T] { |
| 94 | + def indexOfLargest = this.zipWithIndex.maxBy(_._1)._2 |
| 95 | + def indexOfSmallest = this.zipWithIndex.minBy(_._1)._2 |
| 96 | +} |
| 97 | +``` |
| 98 | + |
| 99 | +There can be only one parameter clause following a type pattern and it must be implicit. As usual, one can combine context bounds and implicit evidence parameters. |
| 100 | + |
| 101 | +### Toplevel Type Variables |
| 102 | + |
| 103 | +A type pattern consisting of a top-level typevariable introduces a fully generic extension. For instance, the following extension introduces `x ~ y` as an alias |
| 104 | +for `(x, y)`: |
| 105 | + |
| 106 | +```scala |
| 107 | +extension InfixPair[T] for T { |
| 108 | + def ~ [U](that: U) = (this, that) |
| 109 | +} |
| 110 | +``` |
| 111 | + |
| 112 | +As a larger example, here is a way to define constructs for checking arbitrary postconditions using `ensuring` so that the checked result can be referred to simply by `result`. The example combines opaque aliases, implicit function types, and extensions to provide a zero-overhead abstraction. |
| 113 | + |
| 114 | +```scala |
| 115 | +object PostConditions { |
| 116 | + opaque type WrappedResult[T] = T |
| 117 | + |
| 118 | + private object WrappedResult { |
| 119 | + def wrap[T](x: T): WrappedResult[T] = x |
| 120 | + def unwrap[T](x: WrappedResult[T]): T = x |
| 121 | + } |
| 122 | + |
| 123 | + def result[T](implicit er: WrappedResult[T]): T = WrappedResult.unwrap(er) |
| 124 | + |
| 125 | + extenson Ensuring[T] for T { |
| 126 | + def ensuring(condition: implicit WrappedResult[T] => Boolean): T = { |
| 127 | + implicit val wrapped = WrappedResult.wrap(this) |
| 128 | + assert(condition) |
| 129 | + this |
| 130 | + } |
| 131 | + } |
| 132 | +} |
| 133 | +object Test { |
| 134 | + import PostConditions._ |
| 135 | + val s = List(1, 2, 3).sum.ensuring(result == 6) |
| 136 | +} |
| 137 | +``` |
| 138 | +**Explanations**: We use an implicit function type `implicit WrappedResult[T] => Boolean` |
| 139 | +as the type of the condition of `ensuring`. An argument condition to `ensuring` such as |
| 140 | +`(result == 6)` will therefore have an implicit value of type `WrappedResult[T]` in scope |
| 141 | +to pass along to the `result` method. `WrappedResult` is a fresh type, to make sure that we do not get unwanted implicits in scope (this is good practice in all cases where implicit parameters are involved). Since `WrappedResult` is an opaque type alias, its values need not be boxed, and since `ensuring` is added as an extension method, its argument does not need boxing either. Hence, the implementation of `ensuring` is as about as efficient as the best possible code one could write by hand: |
| 142 | + |
| 143 | + { val result = List(1, 2, 3).sum |
| 144 | + assert(result == 6) |
| 145 | + result |
| 146 | + } |
0 commit comments