0

Say, I have:

var buffer = StringBuffer();
buffer.toString(); // works (understandable)

buffer.write('foo').toString(); // fails because `write` returns `void` (understandable)

buffer..write('bar').toString(); // but why does it fail?

You can see buffer..write('bar') returns a StringBuffer instance, and I should be able to call toString() on that instance. But why it doesn't work that way.


PS: I know I can use buffer..write('bar')..toString() to make it work but my question is not how to make that work rather I want to know the reason why it didn't work.

iDecode
  • 22,623
  • 19
  • 99
  • 186

1 Answers1

1

Because that is how the cascade operator is suppose to work.

buffer..write('bar').toString();

Is equal to do:

buffer.write('bar').toString();

Where:

buffer..write('bar')..toString();

Is equal to:

buffer.write('bar');
buffer.toString();

What you can do to make your example works is to add bracket like this so we changes the order of how each part is linked:

(buffer..write('bar')).toString();

Also found this answer which also gives some details about this behavior: How do method cascades work exactly in dart?

julemand101
  • 28,470
  • 5
  • 52
  • 48