Control Flow
If Case Pattern Match
Dart 3's if (value case Pattern) checks a value against a pattern and, when it matches, destructures the parts into fresh local variables for the then branch. A record pattern (int id, String name) matches a 2-record whose first field is an int and second is a String, binding id and name to the field values. If the pattern does not match, control falls through to the else branch and no bindings are introduced.
Program
Play the program to match an Object against a typed record pattern, destructure id and name, and print a labeled summary.
if_case.dart
Replay: real traced execution (multi-file project)
void main() {
Object data = (42, 'Ada');
String label;
if (data case (int id, String name)) {
label = 'id=$id name=$name';
} else {
label = 'unknown';
}
print(label);
}
data ← (42, Ada) as Object
1void main() {2 Object data = (42, 'Ada');3 String label;values this step(42, Ada) as Objectdatalabel ← <uninitialized>
2Object data = (42, 'Ada');3String label;4if (data case (int id, String name)) {values this step<uninitialized>labelmatch ← true, id ← 42, name ← Ada
3String label;4if (data case (int id, String name)) {5 label = 'id=$id name=$name';values this steptruematch42idAdaname(42, Ada)datalabel ← id=42 name=Ada
4if (data case (int id, String name)) {5 label = 'id=$id name=$name';6} else {values this stepid=42 name=Adalabel42idAdanameprint(label);
8 }9 print(label);10}outputid=42 name=Adavalues this stepid=42 name=Adalabel
Match the Record
datastarts as(42, 'Ada').- The pattern expects an
intfollowed by aString. - The record matches, so
idbecomes42andnamebecomesAda. - The label becomes
id=42 name=Ada. | Record part | Bound name | Value | | --- | --- | --- | | first field |id|42| | second field |name|Ada|
if-case
`if (value case Pattern) { ... }` runs the `then` branch when `value` matches `Pattern` and skips to `else` otherwise. The pattern's bindings exist only inside the matched branch.
record pattern
`(int id, String name)` matches a 2-record with field types `int` and `String`, then binds the field values to fresh locals `id` and `name`.
else branch
When the pattern does not match, the `else` arm runs and the pattern's `id`/`name` are never bound. Both arms still assign `label`, so the variable is definitely initialized before `print`.
Exercise: if_case.dart
Use if-case to match the record (42, 'Ada') and print the id-name label