Question

The following example (1) reads a file and prints the contents without explicitly assigning the file contents to a variable (ie. “.then(stdout.write)”). However, if I want to do more than just print the contents (2), I need to assign the contents to a variable (I think).

Is it possible to achieve that (print the contents and do more), without assigning the text of the file to a variable?

In the first example, is an implicit variable created? Or, put another way, does example1 use less resources by not creating an explicit variable?

//Example 1:
import 'dart:io';
void main() {
  new File(new Options().script)
    .readAsString(encoding: Encoding.ASCII)
    .then(stdout.write)
    .catchError((oError) => print(oError));
  print("Reading file ...\n");
}

//Example 2:
import 'dart:io';
void main() {
  new File(new Options().script)
    .readAsString(encoding: Encoding.ASCII)
    .then((String sText) {
      stdout.write(sText+"\n\n");
      print ('Completed');
    })
    .catchError((oError) => print(oError));
  print("Reading file ...\n");
}
Was it helpful?

Solution

In the first example, this:

.then(stdout.write)

is equivalent to this:

.then((String sText) {
  stdout.write(sText);
})

Technically there's one more function call, and you have one more variable, which should cost you a few bytes (I'm not sure on the exact implementation). Strings are immutable; you are only receiving a reference to the String, so you are not saving resources (other than the function call and a few bytes of memory) by using second version.

Whatever it is you want to do with the contents of the String probably will involve using resources, of course, but that shouldn't be an issue unless the file is huge.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top