typestar

late y lo perezoso en Dart

Difiere la inicialización sin volverte anulable.

// late defers initialization past the constructor without going
// nullable; a late final with an initializer runs lazily, on first use.
class SurveyDay {
  late final String weatherNote = _fetchWeather();
  late String leader;

  String _fetchWeather() {
    print('(fetching the forecast now)');
    return 'light rain, SW 12';
  }
}

void main() {
  final day = SurveyDay();
  day.leader = 'Rae';
  print('Leader: ${day.leader}');
  // First touch triggers the lazy initializer, exactly once.
  print('Weather: ${day.weatherNote}');
  print('Again: ${day.weatherNote}');
}

Cómo funciona

  1. late String leader promete asignación antes de la primera lectura.
  2. late final con inicializador corre perezoso, al primer toque.
  3. El print muestra que el fetch ocurre exactamente una vez.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
20
Caracteres a escribir
548
Tokens
95
Ritmo de tres estrellas
65 tpm

Al ritmo de tres estrellas de 65 tokens por minuto, este intento toma unos 88 segundos.

Escribe este fragmento

Paso 3 de 3 en Seguridad ante null; paso 18 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →