Home > OS >  What is the use for a late local variable?
What is the use for a late local variable?

Time:08-28

In Dart, we can declare a local variable without initializing it (and yes, it works with null safety too):

void conditionalInit(bool something) {
  int x;

  if (something) {
    x = 1;
    print(x); // OK
  }
}

If so, what is the added benefit of late modifier? The only one I can think of is that it silences the error of messy conditions like this:

void conditionalInit(bool something) {
  int x;

  if (something) {
    x = 1;
    print(x); // OK
  }

  if (something) {
    print(x); // This only compiles with late declaration
  }
}

But that should be avoided anyway.

So is there a legitimate use for local late variables?

CodePudding user response:

Here is one possible use for a local late variable:

import 'dart:async';

Stream<int> countToFive() {
  late StreamController<int> controller;

  controller = StreamController(
    onListen: () {
      for (int i = 0; i < 5; i  ) {
        controller.add(i   1);
      }
      controller.close();
    },
  );
  
  return controller.stream;
}

Future<void> main() async {
  await for (final number in countToFive()) {
    print(number);
  }
}

Because controller is late it is possible to reference controller within the onListen callback passed into the constructor of the StreamController.

CodePudding user response:

I think the main use case is lazy initialization. A late variable will only be evaluated when it is accessed, which can be useful for costly computations which may not be required at runtime.

CodePudding user response:

late is also useful to assign immutable final variables after initialization.

void conditionalInit(bool something) {
    late final int x;

    if (something) {
        x = 1;
        print(x); // OK
    }

} }

  •  Tags:  
  • dart
  • Related