typestar

Patrones en Dart

Desestructura y prueba en un solo movimiento, con guardas.

void main() {
  final reading = ('gust', 31);

  // Patterns destructure and test in one motion.
  final (kind, value) = reading;
  print('$kind at $value kts');

  // switch patterns guard with when and bind what they match.
  final note = switch (reading) {
    ('gust', final v) when v > 25 => 'secure the scope: $v kts',
    ('gust', final v) => 'breezy: $v kts',
    (final k, _) => 'unhandled reading kind: $k',
  };
  print(note);

  // if-case tries one pattern without a full switch.
  if (reading case (_, > 30)) {
    print('Log an equipment check');
  }
}

Cómo funciona

  1. final (kind, value) = reading desempaca un record.
  2. Los brazos del switch atan con final v y guardan con when.
  3. if (reading case (_, > 30)) prueba un patrón en línea.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
20
Caracteres a escribir
529
Tokens
128
Ritmo de tres estrellas
60 tpm

Al ritmo de tres estrellas de 60 tokens por minuto, este intento toma unos 128 segundos.

Escribe este fragmento

Paso 2 de 3 en Records y patrones; paso 20 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →