|
| 1 | +--- |
| 2 | +layout: doc-page |
| 3 | +title: "Context Functions" |
| 4 | +--- |
| 5 | + |
| 6 | +_Context functions_ are functions with (only) context parameters. |
| 7 | +Their types are _context function types_. Here is an example of a context function type: |
| 8 | + |
| 9 | +```scala |
| 10 | +type Executable[T] = ExecutionContext ?=> T |
| 11 | +``` |
| 12 | +Context function are written using `?=>` as the "arrow" sign. |
| 13 | +They are applied to synthesized arguments, in |
| 14 | +the same way methods with context parameters is applied. For instance: |
| 15 | +```scala |
| 16 | + given ec as ExecutionContext = ... |
| 17 | + |
| 18 | + def f(x: Int): Executable[Int] = ... |
| 19 | + |
| 20 | + f(2).with(ec) // explicit argument |
| 21 | + f(2) // argument is inferred |
| 22 | +``` |
| 23 | +Conversely, if the expected type of an expression `E` is a context function type |
| 24 | +`(T_1, ..., T_n) ?=> U` and `E` is not already an |
| 25 | +context function literal, `E` is converted to an context function literal by rewriting to |
| 26 | +```scala |
| 27 | + (x_1: T1, ..., x_n: Tn) ?=> E |
| 28 | +``` |
| 29 | +where the names `x_1`, ..., `x_n` are arbitrary. This expansion is performed |
| 30 | +before the expression `E` is typechecked, which means that `x_1`, ..., `x_n` |
| 31 | +are available as givens in `E`. |
| 32 | + |
| 33 | +Like their types, context function literals are written using `?=>` as the arrow between parameters and results. They differ from normal function literals in that their types are context function types. |
| 34 | + |
| 35 | +For example, continuing with the previous definitions, |
| 36 | +```scala |
| 37 | + def g(arg: Executable[Int]) = ... |
| 38 | + |
| 39 | + g(22) // is expanded to g((ev: ExecutionContext) ?=> 22) |
| 40 | + |
| 41 | + g(f(2)) // is expanded to g((ev: ExecutionContext) ?=> f(2).with(ev)) |
| 42 | + |
| 43 | + g((ctx: ExecutionContext) ?=> f(22).with(ctx)) // is left as it is |
| 44 | +``` |
| 45 | +### Example: Builder Pattern |
| 46 | + |
| 47 | +Context function types have considerable expressive power. For |
| 48 | +instance, here is how they can support the "builder pattern", where |
| 49 | +the aim is to construct tables like this: |
| 50 | +```scala |
| 51 | + table { |
| 52 | + row { |
| 53 | + cell("top left") |
| 54 | + cell("top right") |
| 55 | + } |
| 56 | + row { |
| 57 | + cell("bottom left") |
| 58 | + cell("bottom right") |
| 59 | + } |
| 60 | + } |
| 61 | +``` |
| 62 | +The idea is to define classes for `Table` and `Row` that allow |
| 63 | +addition of elements via `add`: |
| 64 | +```scala |
| 65 | + class Table { |
| 66 | + val rows = new ArrayBuffer[Row] |
| 67 | + def add(r: Row): Unit = rows += r |
| 68 | + override def toString = rows.mkString("Table(", ", ", ")") |
| 69 | + } |
| 70 | + |
| 71 | + class Row { |
| 72 | + val cells = new ArrayBuffer[Cell] |
| 73 | + def add(c: Cell): Unit = cells += c |
| 74 | + override def toString = cells.mkString("Row(", ", ", ")") |
| 75 | + } |
| 76 | + |
| 77 | + case class Cell(elem: String) |
| 78 | +``` |
| 79 | +Then, the `table`, `row` and `cell` constructor methods can be defined |
| 80 | +with context function types as parameters to avoid the plumbing boilerplate |
| 81 | +that would otherwise be necessary. |
| 82 | +```scala |
| 83 | + def table(init: Table ?=> Unit) = { |
| 84 | + given t as Table |
| 85 | + init |
| 86 | + t |
| 87 | + } |
| 88 | + |
| 89 | + def row(init: Row ?=> Unit) with (t: Table) = { |
| 90 | + given r as Row |
| 91 | + init |
| 92 | + t.add(r) |
| 93 | + } |
| 94 | + |
| 95 | + def cell(str: String) with (r: Row) = |
| 96 | + r.add(new Cell(str)) |
| 97 | +``` |
| 98 | +With that setup, the table construction code above compiles and expands to: |
| 99 | +```scala |
| 100 | + table { ($t: Table) ?=> |
| 101 | + |
| 102 | + row { ($r: Row) ?=> |
| 103 | + cell("top left").with($r) |
| 104 | + cell("top right").with($r) |
| 105 | + }.with($t) |
| 106 | + |
| 107 | + row { ($r: Row) ?=> |
| 108 | + cell("bottom left").with($r) |
| 109 | + cell("bottom right").with($r) |
| 110 | + }.with($t) |
| 111 | + } |
| 112 | +``` |
| 113 | +### Example: Postconditions |
| 114 | + |
| 115 | +As a larger example, here is a way to define constructs for checking arbitrary postconditions using an extension method `ensuring` so that the checked result can be referred to simply by `result`. The example combines opaque aliases, context function types, and extension methods to provide a zero-overhead abstraction. |
| 116 | + |
| 117 | +```scala |
| 118 | +object PostConditions { |
| 119 | + opaque type WrappedResult[T] = T |
| 120 | + |
| 121 | + def result[T] with (r: WrappedResult[T]) : T = r |
| 122 | + |
| 123 | + def (x: T) ensuring[T](condition: WrappedResult[T] ?=> Boolean): T = { |
| 124 | + assert(condition.with(x)) |
| 125 | + x |
| 126 | + } |
| 127 | +} |
| 128 | +import PostConditions.{ensuring, result} |
| 129 | + |
| 130 | +val s = List(1, 2, 3).sum.ensuring(result == 6) |
| 131 | +``` |
| 132 | +**Explanations**: We use a context function type `WrappedResult[T] ?=> Boolean` |
| 133 | +as the type of the condition of `ensuring`. An argument to `ensuring` such as |
| 134 | +`(result == 6)` will therefore have a given of type `WrappedResult[T]` in |
| 135 | +scope to pass along to the `result` method. `WrappedResult` is a fresh type, to make sure |
| 136 | +that we do not get unwanted givens in scope (this is good practice in all cases |
| 137 | +where context parameters are involved). Since `WrappedResult` is an opaque type alias, its |
| 138 | +values need not be boxed, and since `ensuring` is added as an extension method, its argument |
| 139 | +does not need boxing either. Hence, the implementation of `ensuring` is as about as efficient |
| 140 | +as the best possible code one could write by hand: |
| 141 | + |
| 142 | +```scala |
| 143 | +{ val result = List(1, 2, 3).sum |
| 144 | + assert(result == 6) |
| 145 | + result |
| 146 | +} |
| 147 | +``` |
| 148 | +### Reference |
| 149 | + |
| 150 | +For more info, see the [blog article](https://www.scala-lang.org/blog/2016/12/07/implicit-function-types.html), |
| 151 | +(which uses a different syntax that has been superseded). |
| 152 | + |
| 153 | +[More details](./implicit-function-types-spec.md) |
0 commit comments