Skip to content

Commit 48614d7

Browse files
committed
Add doc page for new control syntax
1 parent 58188e5 commit 48614d7

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
---
2+
layout: doc-page
3+
title: New Control Syntax
4+
---
5+
6+
Scala 3 has a new "quiet" syntax for control expressions that does not rely in
7+
enclosing the condition in parentheses, and also allows to drop parentheses or braces
8+
around the generators of a `for`-expression. Examples:
9+
```scala
10+
if x < 0 then -x else x
11+
12+
while x >= 0 do x = f(x)
13+
14+
for x <- xs if x > 0
15+
yield x * x
16+
17+
for
18+
x <- xs
19+
y <- ys
20+
do
21+
println(x + y)
22+
```
23+
24+
The rules in detail are:
25+
26+
- The condition of an `if`-expression can be written without enclosing parentheses if it is followed by a `then`.
27+
- The condition of a `while`-loop can be written without enclosing parentheses if it is followed by a `do`.
28+
- The enumerators of a `for`-expression can be written without enclosing parentheses or braces if they are followed by a `yield` or `do`.
29+
- A `do` in a `for`-expression expresses a `for`-loop.
30+
- Newline characters are not statement separators in a condition of an `if` or a `while`.
31+
So the meaning of newlines is the same no matter whether parentheses are present
32+
or absent.
33+
- Newline characters are statement separators in the enumerators of a `for`-expression if and only if the first generator of the `for` expression appears on a new line.
34+
35+
To illustrate the last rule above, compare
36+
```scala
37+
for x <- xs
38+
++ ys // newline not significant here
39+
++ zs // newline not significant here
40+
do println(x)
41+
```
42+
and
43+
```scala
44+
for
45+
x <- xs
46+
y <- xs // newline is significant here
47+
do println(x)
48+
```
49+
50+
### Rewrites
51+
52+
The Dotty compiler can rewrite source code from old syntax and new syntax and back.
53+
When invoked with options `-rewrite -new-syntax` it will rewrite from old to new syntax, dropping parentheses and braces in conditions and enumerators. When invoked with with options `-rewrite -old-syntax` it will rewrite in the reverse direction, inserting parentheses and braces as needed.

docs/sidebar.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,8 @@ sidebar:
101101
url: docs/reference/other-new-features/tupled-function.html
102102
- title: threadUnsafe Annotation
103103
url: docs/reference/other-new-features/threadUnsafe-annotation.html
104+
- title: New Control Syntax
105+
url: docs/reference/other-new-features/control-syntax.html
104106
- title: Other Changed Features
105107
subsection:
106108
- title: Structural Types

0 commit comments

Comments
 (0)