Tipos anulables en Dart
String? admite null; el compilador rastrea cuál tienes.
// String? admits null; plain String never does. A map lookup is the
// classic source: the key might not be there.
String? lastFixFor(Map<String, String> log, String species) =>
log[species];
void main() {
final log = {'bittern': 'north scrape'};
final heron = lastFixFor(log, 'heron');
final bittern = lastFixFor(log, 'bittern');
// ?. stops at null; ?? supplies the fallback.
print(heron?.toUpperCase() ?? 'no fix logged');
print(bittern?.toUpperCase() ?? 'no fix logged');
// Promotion: after the check, bittern is plain String.
if (bittern != null) {
print('Fix is ${bittern.length} chars');
}
}
Cómo funciona
- Una búsqueda en map devuelve
String?— la clave puede faltar. ?.se detiene en null;??provee el respaldo.- Tras
if (bittern != null)el tipo se promueve aStringa secas.
Palabras clave y builtins usados aquí
Stringfinalifvoid
El intento, en números
- Líneas
- 19
- Caracteres a escribir
- 603
- Tokens
- 121
- Ritmo de tres estrellas
- 70 tpm
Al ritmo de tres estrellas de 70 tokens por minuto, este intento toma unos 104 segundos.
Paso 1 de 3 en Seguridad ante null; paso 16 de 27 en Fundamentos del lenguaje.