Search code examples
dartmethod-cascades

How do method cascades work exactly in dart?


As stated in the dart article:

The ".." syntax invokes a method (or setter or getter) but discards the result, and returns the original receiver instead.

So I assumed that this would work:

myList..clear().addAll(otherList);

which gave me the error that I can't call .addAll on null.

So apparently . precedes .. so that .addAll has been invoked on the result of .clear().

I figure now that I have two possibilities to write this:

  1. myList..clear()..addAll(otherList);
  2. (myList..clear()).addAll(otherList); (If I wanted to get the result of .addAll().

Is this correct? If yes, why the decision to give . precedence? It seems very counterintuitive. Is it to avoid syntax like this: myList(..clear().useResultOfClear()).addAll(otherList);?


Solution

  • You can read the article from Gilad Bracha : Method Cascades in Dart. At its ends, you will see many examples.

    See also this answer of Lasse Nielsen about operator precedence :

    It helps to think of ".." as not really an operator, but more like a scoping construct (like parentheses). It creates a new scope from the ".." to either the next "..", or the first other scope delimiter (";", ")", "}" or similar).

    Basically, a..b().c() is the same as (t){t.b().c(); return t;}(a)