dart-lang / dart-lang/language

unify the syntax of if-statements, collection ifs and the ternary operator

Open
#729 13 comments 15 reactions 0 assignees View on GitHub
feature
Dominant language
TeX
Stars
2.9k
Forks
239
Avg merge
2d 18h
Merged PRs (30d)
14

Description

These three language constructs are closely related:
- if-statements
- ternary operator
- collection-ifs

I think the development of NNBD, which also introduces new syntax, offers an opportunity to merge the semantics and syntax.

Would it be possible to do something like this:
- convert if-statements to expressions.
- deprecate the ternary operator
- convert collection-ifs to if-expressions

It seems to me that the first two points should be straightforward. All if-statements are now expressions. An if-expression with return type void is essentially an if-statement, this covers existing code.

The introduction of NNBD is probably very much needed for this feature, since an if-expression without an else block will return an optional value. So if the else branch doesn't exist, or if either branch returns a nullable type, the type of the if-expression is nullable.

Based on this, the ternary operator could be deprecated.

Well, I am aware that now my proposal breaks. Collection-ifs are now syntactically identical to an if-expression without an else block. And instead of filtering elements in the collection, they will insert lots of nulls.

As a fix, I would be happy with something like a 'remove-null' operator. Maybe `??`.
So the code would look like this:
```

var nav = [
'Home',
if (promoActive) 'Outlet'
]; // should produce a warning about nullable code

List nav = [
'Home',
if (promoActive) 'Outlet'
]; // works

List nav = [
'Home',
if (promoActive) 'Outlet'
]; // compiler error

List nav = [
'Home',
if (promoActive) 'Outlet'
]??; // works

```

This language change would introduce if-expressions and merge the syntax of collection-ifs. Also, it would free up the syntax of the ternary operator, which could then be used for null checks. Actually, I think that the graceful deprecation of the ternary operator is the real advantage to be had here. This is directly related to #376

Contributor guide

Open the contributing guide

Research direction

Start by reading the proposed syntax and semantics in this issue, then review the related discussion in #376. Done would require an agreed language-design decision covering if-expressions, collection-ifs, nullable values, and the ternary operator; the issue names no files or tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
dart
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
20/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.