|
| 1 | +--- |
| 2 | +layout: doc-page |
| 3 | +title: "Polymorphic Function Types" |
| 4 | +--- |
| 5 | + |
| 6 | +A polymorphic function type is a function type which accepts type parameters. |
| 7 | +For example: |
| 8 | +```scala |
| 9 | +// A polymorphic method: |
| 10 | +def foo[A](xs: List[A]): List[A] = xs.reverse |
| 11 | + |
| 12 | +// A polymorphic function value: |
| 13 | +val bar: [A] => List[A] => List[A] |
| 14 | +// ^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 15 | +// a polymorphic function type |
| 16 | + = [A] => (xs: List[A]) => foo[A](xs) |
| 17 | +``` |
| 18 | +Scala already has _polymorphic methods_, i.e. methods which accepts type parameters. |
| 19 | +Method `foo` above is an example, accepting a type parameter `A`. |
| 20 | +So far, it |
| 21 | +was not possible to turn such methods into polymorphic function values like `bar` above, |
| 22 | +which can be passed as parameters to other functions, or returned as results. |
| 23 | + |
| 24 | +In Dotty this is now possible. The type of the `bar` value above is |
| 25 | + |
| 26 | +```scala |
| 27 | +[A] => List[A] => List[A] |
| 28 | +``` |
| 29 | + |
| 30 | +This type describes function values which take a type `A` as a parameter, |
| 31 | +then take a list of type `List[A]`, and return a list of the same type `List[A]`. |
| 32 | + |
| 33 | +[More details](https://github.com/lampepfl/dotty/pull/4672) |
| 34 | + |
| 35 | +### Relationship With Type Lambdas |
| 36 | + |
| 37 | +Polymorphic function types are not to be confused with |
| 38 | +[_type lambdas_](new-types/type-lambdas.md). |
| 39 | +While the former describes the _type_ of a polymorphic _value_, |
| 40 | +the latter is an actual function value _at the type level_. |
| 41 | + |
| 42 | +A good way of understanding the difference is to notice that |
| 43 | +**_type lambdas are applied in types, |
| 44 | +whereas polymorphic functions are applied in terms_**: |
| 45 | +One would call the function `bar` above |
| 46 | +by passing it a type argument `bar[Int]` _within a method body_. |
| 47 | +On the other hand, given a type lambda such as `type F = [A] =>> List[A]`, |
| 48 | +one would call `F` _withing a type expression_, as in `type Bar = F[Int]`. |
0 commit comments