Skip to content

Commit 512baa3

Browse files
Docs: Add section on dependent typing (impl in this PR)
1 parent 0166e5f commit 512baa3

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

docs/docs/reference/new-types/match-types.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,26 @@ type Concat[Xs <: Tuple, Ys <: Tuple] <: Tuple = Xs match {
5555

5656
In this definition, every instance of `Concat[A, B]`, whether reducible or not, is known to be a subtype of `Tuple`. This is necessary to make the recursive invocation `x *: Concat[xs, Ys]` type check, since `*:` demands a `Tuple` as its right operand.
5757

58+
## Dependent typing
59+
60+
Match types can be used to define dependently type methods. For instance, here is value level counterpart to the`LeafElem` defined above (note the use of the match type as return type):
61+
62+
```scala
63+
def leafElem[X](x: X): LeafElem[X] = x match {
64+
case x: String => x.charAt(0)
65+
case x: Array[t] => leafElem(x(9))
66+
case x: Iterable[t] => leafElem(x.next())
67+
case x: AnyVal => x
68+
}
69+
```
70+
71+
This special mode of typing for match expressions is only used when the following conditions are met:
72+
73+
1. The match expression patterns do not have guards
74+
2. The match expression scrutinee's type is a subtype of the match type scrutinee's type
75+
3. The match expression and the match type have the same number of cases
76+
4. The match expression patterns are all [Typed Patterns](https://scala-lang.org/files/archive/spec/2.13/08-pattern-matching.html#typed-patterns), and these types are `=:=` to their corresponding type patterns in the match type
77+
5878
## Representation of Match Types
5979

6080
The internal representation of a match type

0 commit comments

Comments
 (0)