Skip to content

Commit

Permalink
Add doc page for new control syntax
Browse files Browse the repository at this point in the history
  • Loading branch information
odersky committed Aug 11, 2019
1 parent d4ac997 commit 9829b01
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
53 changes: 53 additions & 0 deletions docs/docs/reference/other-new-features/control-syntax.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
---
layout: doc-page
title: New Control Syntax
---

Scala 3 has a new "quiet" syntax for control expressions that does not rely in
enclosing the condition in parentheses, and also allows to drop parentheses or braces
around the generators of a `for`-expression. Examples:
```scala
if x < 0 then -x else x

while x >= 0 do x = f(x)

for x <- xs if x > 0
yield x * x

for
x <- xs
y <- ys
do
println(x + y)
```

The rules in detail are:

- The condition of an `if`-expression can be written without enclosing parentheses if it is followed by a `then`.
- The condition of a `while`-loop can be written without enclosing parentheses if it is followed by a `do`.
- The enumerators of a `for`-expression can be written without enclosing parentheses or braces if they are followed by a `yield` or `do`.
- A `do` in a `for`-expression expresses a `for`-loop.
- Newline characters are not statement separators in a condition of an `if` or a `while`.
So the meaning of newlines is the same no matter whether parentheses are present
or absent.
- 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.

To illustrate the last rule above, compare
```scala
for x <- xs
++ ys // newline not significant here
++ zs // newline not significant here
do println(x)
```
and
```scala
for
x <- xs
y <- xs // newline is significant here
do println(x)
```

### Rewrites

The Dotty compiler can rewrite source code from old syntax and new syntax and back.
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.
2 changes: 2 additions & 0 deletions docs/sidebar.yml
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@ sidebar:
url: docs/reference/other-new-features/tupled-function.html
- title: threadUnsafe Annotation
url: docs/reference/other-new-features/threadUnsafe-annotation.html
- title: New Control Syntax
url: docs/reference/other-new-features/control-syntax.html
- title: Other Changed Features
subsection:
- title: Structural Types
Expand Down

0 comments on commit 9829b01

Please sign in to comment.