Description
Related: #1066 #1660 dart-lang/sdk#42652
EDITS:
- Changed syntax from
..
to...
to avoid collision with cascade syntax
I'm proposing a mostly complete range syntax as seen in other languages such as a Zig and Rust. The range would be inclusive on both ends.
It would be something like this:
const List<String> items = ['foo', 'bar', 'bizz'];
final [foo, bar] = items[0...1]; // returns a list with the first two items "foo" and "bar"
It can also be used to create lists:
final List<int> numbers = 1...10; // makes an inclusive list with the numbers 1-10
It can be used to make for loops easier:
for (final i in 1...10) {
print(i); // prints 1 though 10
}
for (final i in 10...1) { // we can even go backwards!
print(i); // prints 10 through 1
}
Could be used to iterate through string characters (needs work):
for (final c in 'a'...'z') {
print(c); // prints "a" through "z"
}
This syntax with strings would probably need some work, as commented in a related issue above, character strings could be introduced like c'a'
and might be required here because introducing a character type would be a major breaking change if you would define a character literal with single quotes.
Switch statements/expressions:
const int value = 10;
switch (value) {
case 1...5:
print("value is between 1 and 5");
case 6...10:
print("value is between 6 and 10"); // this prints
default:
print("value is $value");
}
Some other questions that need to be answered
Should ranges always be known at compile time?
Should we be able to do something like this:
// Imagine [start] and [end] are fetched some some data source
final int start = 0;
final int end = 5;
final List<int> inBetween = start...end; // should this be valid?