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
late String leaderpromete asignación antes de la primera lectura.late finalcon inicializador corre perezoso, al primer toque.- El print muestra que el fetch ocurre exactamente una vez.
Palabras clave y builtins usados aquí
Stringclassfinallatereturnvoid
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.
Paso 3 de 3 en Seguridad ante null; paso 18 de 27 en Fundamentos del lenguaje.