Home > OS >  Using for and if without curly braces representing control structures
Using for and if without curly braces representing control structures

Time:09-08

List<Set<String>> iDontGetIt() {
  var test = [
    for (final e in [2, 4, 6])
      if (e == 4) {
         'What?!'
        }
  ];
  return test;
}

If I run this code I return 'test' which is equal to [{What?!}]. I can insinuate that there is an inferred return statement after (y == 4) that is returning {'What?!'}.

However, in my head I would expect to write that code with the curly braces representing the control structure of the code, not an indication that a set should be created:

List<String> iDontGetIt() {
  var test = [
    for (final e in [2, 4, 6]) {
      if (e == 4) {
         return 'What?!';
        }}
  ];
  return test;
}

I would read this to myself as "The test variable is going to equal a list. Inside that list a for loop is going to run looking at each element of the 2,4,6 list. A code block represented by the curly braces will run on each iteration of the loop. The block says that if the element is equal to 4 then we will once again enter a code block inside the curly braces. This second block will return the string 'What?!', placing it in the list. If it the code block above doesn't equal 4, we'll move to the end of the block and then into the next iteration of the loop." Using that logic, if I ran the code I would return test which would be equal to a List<String> ['What?!'].

I'm obviously wrong, because the linter tells me there is Unexpected text 'return', but this goes against how I expect the control structure of code to function. Every time I've come across a for or if statement there are curly braces that explicitly state what code block should run. I even see this on https://dart.dev/guides/language/language-tour#control-flow-statements where they illustrate with curly braces representing code blocks, not the creation of a set.

Can someone help me understand why there is a deviation from the curly braces representing a code block, show me where this is explained on dart.dev, or otherwise just help me understand what's going on?

CodePudding user response:

The difference is that the if and for inside a collection literal contains an expression, not a statement.

The {statements} block statement can contain zero or more statements. Can't use that inside an expression.

As an expression, {"What"} is a set literal. You also cannot use return as an expression.

It's basically the same as the difference between the statements

  { return "What"; }

and

  return {"What"};
  •  Tags:  
  • dart
  • Related