Skip to content

Commit ac825ae

Browse files
Given clause & type-safe pattern bindings
1 parent a26301b commit ac825ae

File tree

1 file changed

+47
-1
lines changed

1 file changed

+47
-1
lines changed

docs/blog/_posts/2019-05-24-15th-dotty-milestone-release.md

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,9 +81,55 @@ To smoothen the migration, the deprecation warnings will only be emitted if you
8181
For more information, see the [documentation](http://dotty.epfl.ch/docs/reference/changed-features/operators.html#the-infix-annotation). Note that the `@alpha` annotation also described in the documentation is a work in progress and is not available in this release.
8282

8383
## `given` clause comes last
84+
In the previous release, you could write something like this:
8485

86+
```scala
87+
implied for String = "foo"
88+
def f(x: Int) given (y: String) (z: Int) = x + z
89+
f(1)(3)
90+
```
91+
92+
Now, however, `given` clauses must come last:
93+
94+
```scala
95+
implied for String = "foo"
96+
def f(x: Int)(z: Int) given (y: String) = x + z
97+
f(1)(3)
98+
```
99+
100+
This change is done to reduce confusion when calling functions with mixed explicit and implied parameters.
101+
102+
## Type-safe Pattern Bindings
103+
```scala
104+
val xs: List[Any] = List(1, 2, 3)
105+
val (x: String) :: _ = xs // error: pattern's type String is more specialized
106+
// than the right hand side expression's type Any
107+
```
108+
109+
The above code will fail with a compile-time error in Dotty 3.1 and in Dotty 3 with the `-strict` flag. In contrast, in Scala 2, the above would have compiled fine but failed on runtime with an exception.
110+
111+
Dotty compiler will allow such a pattern binding only if the pattern is *irrefutable* – that is, if the right-hand side conforms to the pattern's type. E.g. the following is OK:
112+
113+
```scala
114+
val pair = (1, true)
115+
val (x, y) = pair
116+
```
117+
118+
If we want to force the pattern binding if the pattern is not irrefutable, we can do so with an annotation:
119+
120+
```scala
121+
val first :: rest : @unchecked = elems // OK
122+
```
123+
124+
The same is implemented for pattern bindings in `for` expressions:
125+
126+
```scala
127+
val elems: List[Any] = List((1, 2), "hello", (3, 4))
128+
for ((x, y) <- elems) yield (y, x) // error: pattern's type (Any, Any) is more specialized
129+
// than the right hand side expression's type Any
130+
```
85131

86-
### Compatibility: the `@alpha` annotation
132+
For the migration purposes, the above change will only take effect in Dotty 3.1 by default. You can use it from Dotty 3 with the `-strict` flag.
87133

88134

89135
## Other changes

0 commit comments

Comments
 (0)