Thuta Learning
Dart
AdvancedProgrammingအခြေခံ

Records, Patterns & Primary Constructors

Dartသင်ခန်းစာ 1840 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • Positional နဲ့ named record ကို ကြေညာပြီး $1 ဒါမှမဟုတ် field နာမည်နဲ့ ဖတ်နိုင်ဖို့
  • Record, list, map နဲ့ object pattern တွေနဲ့ destructure လုပ်ပြီး guard (when) ပါတဲ့ switch expression ရေးနိုင်ဖို့
  • Exhaustiveness check က ဘာကို ကာကွယ်ပေးလဲ၊ _ catch-all က ဘာကို ဆုံးရှုံးစေလဲ ရှင်းပြနိုင်ဖို့
  • Primary constructor ရေးနည်းကို classic constructor နဲ့ နှိုင်းယှဉ်ပြီး SDK version လိုအပ်ချက်ကို သိဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

Record နဲ့ pattern ကို ရိုးရိုးလေး ပြောရရင်

Record ဆိုတာ value အနည်းငယ်ကို တစ်ပတ်ထုပ်ထားတဲ့ မပြောင်းလဲနိုင်တဲ့ အထုပ်ငယ်လေးပါ၊ class ကို နာမည်ပေး ကြေညာစရာမလိုပါဘူး။ (3, 4) ဒါမှမဟုတ် (name: 'Mia', age: 31) လို့ ရေးလိုက်ရုံနဲ့ ရပါတယ်။ Function တစ်ခုက ရလဒ်နှစ်ခု ပြန်ပေးချင်တဲ့အခါ အသုံးဝင်ပါတယ်။

Pattern ကတော့ ပုံစံတစ်ခုနဲ့ တူလားလို့ စစ်ပြီး တူရင် အစိတ်အပိုင်းတွေကို variable တွေထဲ ထုတ်ပေးတဲ့ template တစ်ခုပါ။ ပို့ဆောင်ပစ္စည်းထုပ်ကို ဖွင့်ရင် 'ဒါ ဘူးတစ်လုံးလား၊ အထဲမှာ ဘာတွေရှိလဲ' လို့ ကြည့်သလိုပါပဲ။ ပုံစံ မကိုက်ရင် ဒီ case ကို ကျော်ပြီး နောက်တစ်ခုကို စမ်းပါတယ်။ Primary constructor ကတော့ class တစ်ခုရဲ့ constructor ကို ပိုတိုတိုရေးခွင့်ပေးတဲ့ ရေးနည်းအသစ်ပါ။

Problem → Why → Solution

ပြဿနာ: ရလဒ်နှစ်ခု ပြန်ချင်ရင် ဘာလုပ်မလဲ

Reading list တစ်ခုထဲက အနိမ့်ဆုံးနဲ့ အမြင့်ဆုံး temperature ကို ပြန်ပေးတဲ့ function လိုပါတယ်။ Dart function က return value တစ်ခုပဲ ပေးနိုင်လို့ အစောပိုင်းမှာ List<double> တစ်ခု ပြန်ပေးပြီး result[0], result[1] လို့ ဖတ်ကြပါတယ်။ ဒါပေမဲ့ အဲဒီ list ထဲမှာ ဘယ်ဟာ အနိမ့်ဆုံးလဲ၊ element ဘယ်နှစ်ခု ပါလဲ ဆိုတာ ဘယ်သူမှ မသိပါဘူး၊ index ပြောင်းသွားရင် compiler က မသတိပေးပါဘူး။

တစ်ခြားလမ်းက ဒီ function တစ်ခုအတွက်ပဲ MinMax class တစ်ခု ကြေညာတာပါ။ ဒါက type-safe ဖြစ်ပေမဲ့ field ၊ constructor နဲ့ ဖိုင်တစ်ခုလုံးလောက် boilerplate ရေးရပြီး နောက်တစ်ရက် ရလဒ်သုံးခု လိုလာရင် class တစ်ခုထပ်ရေးရပါတယ်။

list_as_result.dart
List<double> rangeOf(List<double> values) {
  var lowest = values.first;
  var highest = values.first;
  for (final v in values) {
    if (v < lowest) lowest = v;
    if (v > highest) highest = v;
  }
  return [lowest, highest]; // which slot is which? the type cannot say
}

void main() {
  final result = rangeOf([21.0, -3.2, 95.5]);
  print(result[1] - result[0]);
  print(result[2]); // compiles, then throws a RangeError at run time
}

List က shape ကို မဖော်ပြနိုင်ဘူး

List က element အရေအတွက်နဲ့ အဓိပ္ပာယ်ကို type ထဲမှာ မမှတ်ထားပါဘူး၊ ဒါကြောင့် result[2] က compile ဖြစ်ပြီး run ချိန်မှာမှ RangeError ပေးပါတယ်။ Record ရဲ့ type က (double, double) လို့ ရေးထားလို့ field နှစ်ခုပဲ ရှိကြောင်း compiler သိပြီး ပြင်ပရတဲ့ index ကို compile အချိန်မှာပဲ ပယ်ပါတယ်။ ဒါပေမဲ့ class မရေးရဘဲ ရပါတယ်။

Core concept: record, pattern, exhaustive switch နဲ့ primary constructor

Record မှာ positional field (int, String)၊ named field ({String name, int age}) ဒါမှမဟုတ် နှစ်မျိုးလုံး ပါနိုင်ပါတယ်။ Literal က (1, 'a') နဲ့ (name: 'Mia', age: 31) ပါ။ Positional field တွေကို $1, $2 (၁ ကစ ရေ) နဲ့ ဖတ်ပြီး named field တွေကို နာမည်နဲ့ ဖတ်ပါတယ်။ Record နှစ်ခုက shape တူပြီး field တိုင်း တူရင် equal ဖြစ်ပါတယ်၊ (x: 1, y: 2) == (y: 2, x: 1) က true ပါ၊ record က မပြောင်းလဲနိုင်လို့ setter မရှိပါဘူး။

Pattern က value ရဲ့ ပုံစံကို စစ်ပြီး အစိတ်အပိုင်းတွေကို name တွေနဲ့ ချိတ်ပါတယ်။ ဘယ်မှာသုံးလို့ရလဲဆိုရင် variable declaration (final (a, b) = pair;)၊ assignment ((a, b) = (b, a); လို swap)၊ switch၊ if (value case pattern) နဲ့ for-in ထဲမှာပါ။ Pattern အမျိုးအစားတွေက constant ('boiler')၊ relational (> 90)၊ logical (|| နဲ့ &&)၊ list ([a, ..., b])၊ map ({'id': var id})၊ record၊ object (Point(x: var a)၊ var နဲ့ type စစ်တဲ့ variable (int n) နဲ့ _ wildcard တို့ဖြစ်ပြီး when guard နဲ့ အခြေအနေ ထပ်ထည့်နိုင်ပါတယ်။

Switch expression က တန်ဖိုးတစ်ခု ပြန်ပေးတာမို့ break မလိုဘဲ case တစ်ခုက pattern => value ပုံစံပါ။ အပေါ်ကနေ အောက်ကို စစ်ပြီး ပထမဆုံး ကိုက်တာက နိုင်တယ်၊ ဒါကြောင့် တိကျတဲ့ case ကို အပေါ်မှာ ထားပါ။ Sealed class၊ enum၊ bool ဒါမှမဟုတ် ဒါတွေနဲ့ ဖွဲ့စည်းတဲ့ record ကို switch လုပ်ရင် compiler က exhaustive ဖြစ်မဖြစ် စစ်ပါတယ်၊ case တစ်ခု လိုနေရင် run ချိန် အံ့အားသင့်စရာ မဟုတ်ဘဲ compile error ဖြစ်ပါတယ်။ _ ထည့်လိုက်ရင် exhaustive ဖြစ်သွားပေမဲ့ နောက်ထပ် subtype အသစ်ထပ်ထည့်တဲ့အခါ သတိပေးချက်ကို ဆုံးရှုံးပါတယ်။

Primary constructor က constructor ရဲ့ parameter list ကို class header ထဲ ရွှေ့ထည့်တာပါ: class Point(final int x, final int y);။ Parameter မှာ final ဒါမှမဟုတ် var ပါရင် field ဖြစ်ပြီး မပါရင် သာမန် parameter ပဲ ဖြစ်ပါတယ်။ ဒီ feature က language version 3.13 လိုပါတယ်၊ 3.13.7 မှာ flag မလိုဘဲ ရိုးရိုး dart run နဲ့ လက်ခံတာကို ကိုယ်တိုင် စမ်းကြည့်ထားပါတယ်။ Record နဲ့ မတူတာက ဒီလို class မှာ == နဲ့ toString အလိုအလျောက် မပါပါဘူး။

လိုအပ်ချက်ရွေးရမယ့်အရာ
Function က ရလဒ် ၂-၃ ခုကို behavior မပါဘဲ ပြန်ပေးချင်Record
== ၊ hashCode နဲ့ toString ကို အလကား ရချင်Record
Method၊ validation ပါပြီး တစ်နေရာထက်ပိုသုံးတဲ့ နာမည်ရ typeClass (primary constructor နဲ့ တိုတိုရေးနိုင်)
ပုံစံဝင်၊ အစိတ်အပိုင်းထွက်
  1. Value တစ်ခု ရောက်လာ
  2. Pattern က ပုံစံကို စစ်
  3. ကိုက်ရင် အစိတ်အပိုင်းတွေကို name နဲ့ ချိတ်
  4. ပထမ ကိုက်တဲ့ case က ရလဒ်ပေး

ဘယ် case မှ မကိုက်ရင် ရိုးရိုး type ကို switch လုပ်တဲ့ statement က ကျော်သွားပေမဲ့ exhaustive မဖြစ်တဲ့ switch expression ကတော့ compile မဖြစ်ပါဘူး။

အထွေထွေ ပုံစံ

dart
typedef Name = ({Type field, Type other});     // named record type
(Type, Type) pair() => (first, second);       // positional record
final (a, b) = pair();                        // destructure it
Result f(Name v) => switch (v) {
      (field: constant, other: > limit) => value,
      (field: var x, other: _) when x > 0 => value,
      (field: var x, other: var y) => value,
    };
class Name(final Type field);                 // primary constructor

typedef က record type ကို နာမည်ပေးပြီး switch ထဲမှာ constant၊ relational၊ var pattern နဲ့ guard တွေကို စပ်သုံးနိုင်ပါတယ်။ နောက်ဆုံး case က ကျန်တာအားလုံးကို ဖမ်းလို့ switch က exhaustive ဖြစ်ပါတယ်။

Worked example: sensor reading တွေကို record နဲ့ ခွဲခြားခြင်း

Reading ဆိုတဲ့ named record type ကို typedef နဲ့ နာမည်ပေးထားပါတယ်။ rangeOf က (lowest, highest) ကို record အဖြစ် ပြန်ပေးပြီး describe ကတော့ switch expression နဲ့ pattern သုံးခုကို အပေါ်ကနေ အောက်ကို စစ်ပါတယ်။ ပထမ pattern က နာမည်ကို constant နဲ့ စစ်၊ ဒုတိယ pattern က temperature ကို relational နဲ့ စစ်ပြီး ကျန်တာအားလုံးကို နောက်ဆုံး case က ဖမ်းပါတယ်။

readings.dart
typedef Reading = ({String sensor, double celsius});

// A record lets one function return two values with no helper class.
(double lowest, double highest) rangeOf(List<Reading> readings) {
  var lowest = readings.first.celsius;
  var highest = lowest;
  for (final r in readings) {
    if (r.celsius < lowest) lowest = r.celsius;
    if (r.celsius > highest) highest = r.celsius;
  }
  return (lowest, highest);
}

// A switch expression with record patterns. The last case matches every
// Reading, so the compiler knows the switch is exhaustive.
String describe(Reading reading) => switch (reading) {
      (sensor: 'boiler', celsius: > 90) => 'boiler is overheating',
      (sensor: var name, celsius: < 0) => '$name is freezing',
      (sensor: var name, celsius: var c) => '$name is at ${c.toStringAsFixed(1)} C',
    };

void main() {
  final readings = <Reading>[
    (sensor: 'boiler', celsius: 95.5),
    (sensor: 'garage', celsius: -3.2),
    (sensor: 'office', celsius: 21.0),
  ];

  for (final reading in readings) {
    print(describe(reading));
  }

  final (lowest, highest) = rangeOf(readings);
  print('range: $lowest to $highest');

  // Records compare by value, field by field.
  print(readings.first == (sensor: 'boiler', celsius: 95.5));

  if (readings.last case (sensor: var name, celsius: var c) when c > 20) {
    print('$name is warm');
  }
}

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. Name a record typetypedef Reading = ({String sensor, double celsius});

    typedef က named record type တစ်ခုကို Reading လို့ ခေါ်လို့ရအောင် လုပ်ပါတယ်။ ဒါပေမဲ့ Reading ဟာ class အသစ် မဟုတ်ပါဘူး၊ shape တူတဲ့ record ဟာ Reading ပဲ ဖြစ်ပါတယ်။

  2. Return a recordreturn (lowest, highest);

    ပိတ်ကွင်းနဲ့ ရေးတာတင် record တစ်ခု ဖြစ်ပါတယ်။ Return type (double lowest, double highest) ထဲက နာမည်တွေက စာရွက်ပေါ်က ဖော်ပြချက်သက်သက်၊ ဖတ်ဖို့ကတော့ $1 ဒါမှမဟုတ် destructure လုပ်ရပါတယ်။

  3. Constant and relational patterns(sensor: 'boiler', celsius: > 90) => 'boiler is overheating',

    Record pattern ရဲ့ field တစ်ခုချင်းကို သီးခြား စစ်ပါတယ်: sensor က 'boiler' နဲ့ တူရမယ်၊ celsius က 90 ထက် ကြီးရမယ်၊ နှစ်ခုလုံး မှန်မှသာ ဒီ case ကို ရွေးပါတယ်။

  4. Bind with var(sensor: var name, celsius: < 0) => '$name is freezing',

    var name က sensor field ကို name ထဲ ထည့်ပေးပြီး ညာဘက်က expression မှာ သုံးလို့ရပါတယ်။ ဒီ case က ဘယ် sensor ဖြစ်ဖြစ် 0 အောက်ဆိုရင် ရောက်ပါတယ်။

  5. Destructurefinal (lowest, highest) = rangeOf(readings);

    ဘယ်ဘက်က pattern က ပြန်လာတဲ့ record ကို ခွဲပြီး variable နှစ်ခုအဖြစ် ထုတ်ပေးပါတယ်။ Field အရေအတွက် မကိုက်ရင် compile error ပါ။

  6. Structural equalityprint(readings.first == (sensor: 'boiler', celsius: 95.5));

    Record တွေက object identity နဲ့ မဟုတ်ဘဲ field တန်ဖိုးတွေနဲ့ နှိုင်းယှဉ်လို့ အသစ်ဆောက်တဲ့ record နဲ့ တူရင် true ပါ။ ဒါက ရိုးရိုး class မှာ == ကို ကိုယ်တိုင် override လုပ်မှ ရတာပါ။

You should see
boiler is overheating
garage is freezing
office is at 21.0 C
range: -3.2 to 95.5
true
office is warm

Record အကြောင်း ပိုနက်နက်: positional၊ named နဲ့ equality

Positional field တွေရဲ့ type annotation ထဲက နာမည်တွေ (int x, int y) က documentation သက်သက်ပါ၊ ဖတ်တာကတော့ $1, $2 နဲ့ပဲ။ (int x, int y) p = (1, 2); print(p.x); လို့ ရေးရင် "The getter 'x' isn't defined for the type '(int, int)'." ဆိုတဲ့ error ရပါတယ် (ပြန်ထုတ်ကြည့်ထားပါတယ်)။ နာမည်နဲ့ ဖတ်ချင်ရင် ({int x, int y}) လို named field ကို သုံးပါ။

record_rules.dart
void main() {
  final pair = (1, 'a');
  final person = (name: 'Mia', age: 31);
  final mixed = (1, x: 2);

  print(pair); // (1, a)
  print(person); // (age: 31, name: Mia)  named fields are printed sorted
  print(mixed); // (1, x: 2)
  print(pair.$1 + person.age);

  print((1, 2) == (1, 2)); // true: same shape, same values
  print((x: 1, y: 2) == (y: 2, x: 1)); // true: order of named fields is irrelevant
  print((1, 2) == (2, 1)); // false: positional order matters

  var a = 1, b = 2;
  (a, b) = (b, a); // swap without a temporary
  print('$a $b');

  Object o = (1, 2);
  print(o is (int, int)); // true
  print(o is (int, String)); // false
}

ဒီ code က (1, a)၊ (age: 31, name: Mia)၊ (1, x: 2) နဲ့ 32 ကို print ထုတ်ပြီး ဆက်ပြီး true, true, false, '2 1', true, false ကို print ထုတ်ပါတယ်။ Record ကို ပြင်လို့မရပါဘူး၊ pair.$1 = 5 လို့ရေးရင် "The setter '$1' isn't defined" ဆိုပြီး compile မဖြစ်ပါဘူး။ Field နာမည်ကို hashCode, toString လို Object ရဲ့ member နာမည်နဲ့ တူအောင်လည်း မပေးရပါဘူး။

Pattern စာရင်း: list, map, object, relational နဲ့ guard

classify function တစ်ခုထဲမှာ pattern အမျိုးအစားအများစုကို တွေ့ရပါတယ်။ Case တွေက အပေါ်ကနေ အောက်ကို စစ်တာမို့ 0 ကို int n ထက် အရင်ထားပြီး guard ပါတဲ့ int n when n < 0 ကို guard မပါတဲ့ int n ရှေ့မှာ ထားပါတယ်။ [var first, ..., var last] က element နှစ်ခုနဲ့အထက်ရှိတဲ့ list ကိုပဲ ဖမ်းပါတယ်၊ တစ်ခုတည်းရှိတာကို [var only] ကို ဖမ်းပါတယ်။

pattern_tour.dart
class Point {
  const Point(this.x, this.y);
  final int x;
  final int y;
}

String classify(Object? value) => switch (value) {
      null => 'nothing',
      0 => 'zero',
      int n when n < 0 => 'negative int $n',
      int n => 'int $n',
      String s when s.isEmpty => 'empty string',
      String s => 'string of ${s.length}',
      [] => 'empty list',
      [var only] => 'one item: $only',
      [var first, ..., var last] => 'list from $first to $last',
      {'id': int id} => 'map with id $id',
      Point(x: 0, y: 0) => 'origin',
      Point(:var x, :var y) => 'point $x,$y',
      (int a, int b) => 'pair sums to ${a + b}',
      _ => 'something else',
    };

String grade(int score) => switch (score) {
      < 0 || > 100 => 'invalid',
      >= 90 => 'A',
      >= 80 => 'B',
      _ => 'C or lower',
    };

void main() {
  final samples = <Object?>[
    null, 0, -4, 7, '', 'hey', [], [1], [1, 2, 3],
    {'id': 5}, const Point(0, 0), const Point(2, 3), (1, 2), 3.5,
  ];
  for (final value in samples) {
    print(classify(value));
  }
  print([grade(95), grade(85), grade(-1), grade(50)]);
}
text
nothing, zero, negative int -4, int 7, empty string, string of 3,
empty list, one item: 1, list from 1 to 3, map with id 5, origin,
point 2,3, pair sums to 3, something else
[A, B, invalid, C or lower]

(အပေါ်က output ကို ကော်မာနဲ့ ဆက်ပြထားတာပါ၊ program က item တစ်ခုကို တစ်ကြောင်းစီ print ထုတ်ပါတယ်။) Sealed type ကို switch လုပ်တဲ့အခါ compiler က case တစ်ခု လိုနေတာကို ပြောပါတယ်: Shape ကို Circle, Rect, Tri နဲ့ ဖွဲ့ထားပြီး Tri ကို မရေးရင် "The type 'Shape' is not exhaustively matched by the switch cases since it doesn't match 'Tri()'." ဆိုတဲ့ error ရပါတယ် (ပြန်ထုတ်ကြည့်ထားပါတယ်)။ ဒါကို lesson 20 မှာ အသေးစိတ် ဆက်ကြည့်ပါမယ်။

Primary constructor: ရေးနည်းအသစ်နဲ့ version လိုအပ်ချက်

SDK version စစ်ပါ

Primary constructor က language version 3.13 လိုတဲ့ feature အသစ်ပါ။ ဒီ lesson ရဲ့ code တွေကို Dart 3.13.7 မှာ ပြေးကြည့်ထားပြီး flag မလိုဘဲ ရိုးရိုး dart run နဲ့ လက်ခံပါတယ်။ SDK အဟောင်း ဒါမှမဟုတ် pubspec.yaml ထဲက language version နိမ့်နေရင်တော့ လက်မခံပါဘူး။ ဒီ lesson ရဲ့ record နဲ့ pattern အပိုင်းတွေက SDK အဟောင်း (Dart 3 အစောပိုင်း) မှာလည်း အလုပ်လုပ်ပါတယ်။

ပထမဆုံး classic constructor နဲ့ primary constructor ကို အပေါ်အောက်ပြထားပါတယ်။ Class header ထဲက parameter မှာ final ရှိရင် field ဖြစ်ပါတယ်။ Optional named parameter၊ default value၊ const class နဲ့ superclass ကို ခေါ်တာ အားလုံး စမ်းထားပါတယ်: initializer list အတွက်ကတော့ class body ထဲမှာ this : ... ဆိုပြီး ရေးပါတယ်။

primary_constructors.dart
// Classic constructor.
class OldPoint {
  const OldPoint(this.x, this.y);

  final int x;
  final int y;
}

// Primary constructor: the parameter list moves into the class header.
class const NewPoint(final int x, final int y);

// Optional named parameter with a default; the body adds extra members.
class Money(final int cents, {final String currency = 'USD'}) {
  String get label => '$currency ${(cents / 100).toStringAsFixed(2)}';
}

// Initializer-list work (assert, other fields) goes in a `this :` part.
class Range(final int low, final int high) {
  final int span;

  this : assert(high >= low), span = high - low;
}

class Base(final String id);

class Child(String id, final int extra) extends Base {
  this : super(id);
}

void main() {
  const a = OldPoint(1, 2);
  const b = NewPoint(1, 2);
  print('${a.x},${a.y} ${b.x},${b.y}');
  print(Money(1999).label);
  print(Money(500, currency: 'EUR').label);
  print(Range(3, 10).span);
  final c = Child('c-1', 7);
  print('${c.id} ${c.extra}');
}
text
1,2 1,2
USD 19.99
EUR 5.00
7
c-1 7

ဒီ code ထဲက assert ကို dart run က default အားဖြင့် မဖွင့်ပါဘူး (Range(10, 3) ကို --enable-asserts မပါဘဲ ပြေးရင် -7 ကို print ထုတ်ပါတယ်၊ ပြန်ထုတ်ကြည့်ထားပါတယ်)၊ ဒါကြောင့် assert ကို validation အစား မအားကိုးပါနဲ့။ Primary constructor class မှာ == ပါ မပါဘူး: Point(1, 2) == Point(1, 2) က false ပြီး print လုပ်ရင် Instance of 'Point' ထွက်ပါတယ်၊ (1, 2) == (1, 2) ကတော့ true ပြီး (1, 2) လို့ print ထွက်ပါတယ်။

Version gate ကို ကိုယ်တိုင် ပြန်ထုတ်ကြည့်နိုင်ပါတယ်: ဖိုင်ရဲ့ ထိပ်ဆုံးမှာ // @dart=3.12 ထည့်ပြီး class Point(final int x, final int y); ကို ပြေးရင် 3.13.7 က "The 'primary-constructors' language feature is disabled for this library." ဆိုပြီး "Try removing the `@dart=` annotation or setting the language version to 3.13 or higher." လို့ ပြောပါတယ်။ final မပါတဲ့ class Point(int x, int y); ကတော့ compile ဖြစ်ပေမဲ့ x နဲ့ y က field မဟုတ်လို့ Point(1, 2).x က "The getter 'x' isn't defined for the type 'Point'." ပါ။

version_gate.dart
// @dart=3.12
// Error on Dart 3.13.7: The 'primary-constructors' language feature is
// disabled for this library.
class Point(final int x, final int y);

void main() {
  print(Point(1, 2).x);
}

လက်တွေ့ project တွေမှာ

လက်တွေ့ project တွေမှာ record နဲ့ pattern ကို ဘယ်မှာ တွေ့ရလဲ

Record တွေက function ကနေ ရလဒ်များစွာ ပြန်ပေးတဲ့နေရာ အားလုံးမှာ သုံးလို့ရပါတယ်: parsing function တစ်ခုက (value, remainingText) ပြန်ပေးတာ၊ Future<(int, String)> ကနေ status code နဲ့ body ပြန်ပေးတာမျိုးပါ။ Pattern တွေကတော့ JSON လို type မသေချာတဲ့ data ကို ဖတ်တဲ့နေရာမှာ အကျိုးအများဆုံးပါပဲ၊ ပုံစံကို စစ်ခြင်းနဲ့ ထုတ်ယူခြင်းကို တစ်ဆင့်တည်းနဲ့ လုပ်လို့ရလို့ပါ။

  • JSON decode လုပ်ထားတဲ့ Map<String, Object?> ကို if (json case {'user': {'name': String name}}) နဲ့ စစ်ပြီး ထုတ်ယူတာ၊ ပုံစံမှားနေရင် else ကိုသွားတာမို့ cast exception မတက်ပါဘူး။
  • Map ကို loop ပတ်တဲ့အခါ for (final MapEntry(:key, :value) in map.entries) လို့ ရေးတာ index ဒါမှမဟုတ် entry.key ကို ထပ်ခါထပ်ခါ မရေးရတော့ပါဘူး။
  • Sealed state (loading, success, error) ကို switch expression နဲ့ UI ဒါမှမဟုတ် log message အဖြစ် ပြောင်းတာ၊ state အသစ်ထပ်ထည့်ရင် compiler က မပြင်ရသေးတဲ့ switch တွေကို ပြပေးပါတယ်။
json_pattern.dart
void main() {
  final json = <String, Object?>{
    'user': {'name': 'Mia', 'tags': ['dev', 'dart']},
  };
  if (json case {'user': {'name': String name, 'tags': [_, var second]}}) {
    print('$name, second tag: $second');
  }

  final broken = <String, Object?>{
    'user': {'name': 42},
  };
  if (broken case {'user': {'name': String name}}) {
    print('name is $name');
  } else {
    print('unexpected shape');
  }

  for (final MapEntry(:key, :value) in {'a': 1, 'b': 2}.entries) {
    print('$key=$value');
  }
}

အမှားများ

Record နဲ့ pattern မှာ ဖြစ်လေ့ရှိတဲ့ အမှားများ

Positional field ကို နာမည်နဲ့ ဖတ်ဖို့ ကြိုးစားခြင်း

(int x, int y) p = (3, 4); လို့ ကြေညာပြီး p.x ရေးရင် "The getter 'x' isn't defined for the type '(int, int)'." ရပါတယ်။ အဲဒီ x နဲ့ y က documentation ပါ။ $1 သုံးပါ၊ destructure လုပ်ပါ (final (x, y) = p;)၊ ဒါမှမဟုတ် named field ({int x, int y}) ကို ရွေးပါ။

Record ကို class ရှိသင့်တဲ့နေရာမှာ သုံးခြင်း

Field ငါးခုပါတဲ့ record ကို function အများကြီးကြား ပို့နေရင် validation၊ method နဲ့ နာမည်ရ type မရှိတာကို နောက်ပိုင်း နှမြောပါလိမ့်မယ်။ Behavior လိုလာရင် ဒါမှမဟုတ် signature တွေမှာ တစ်နေရာထက်ပို ပေါ်လာရင် class (primary constructor နဲ့ တိုတိုရေးနိုင်) ကို ပြောင်းပါ။

Destructuring မှာ field အရေအတွက် မကိုက်ခြင်း

final (a, b) = (1, 2, 3); က "The matched value of type '(int, int, int)' isn't assignable to the required type '(Object?, Object?)'." လို့ error ပေးပါတယ် (ပြန်ထုတ်ကြည့်ထားပါတယ်)။ Compiler က shape ကိုပါ စစ်လို့ တကယ်တမ်းမှာ ဒါက ကောင်းတဲ့ ကာကွယ်မှုပါ၊ ရလဒ်ကို သုံးခုလုံး ခွဲထုတ်ပါ။

Sealed type switch မှာ _ ထည့်ပြီး compiler ကို ပါးစပ်ပိတ်ခြင်း

Shape ကို switch လုပ်ရင် Circle နဲ့ Rect ကို ရေးပြီး _ => 0 ထည့်လိုက်ရင် exhaustive ဖြစ်သွားပါတယ်။ နောက်တစ်နေ့ Tri subtype အသစ်ထပ်ထည့်ရင် compiler က ဘာမှ မပြောတော့ဘဲ Tri က 0 ကို ရပါတော့တယ်။ Subtype အားလုံးကို တစ်ခုချင်း စာရင်းပြုစုပါ။

Primary constructor parameter မှာ final မေ့ခြင်း

class Point(int x, int y); က compile ဖြစ်ပေမဲ့ x နဲ့ y က constructor parameter သက်သက်၊ field မဟုတ်လို့ Point(1, 2).x က "The getter 'x' isn't defined for the type 'Point'." ပါ (ပြန်ထုတ်ကြည့်ထားပါတယ်)။ Field လိုချင်ရင် final ဒါမှမဟုတ် var ထည့်ပါ။

Best Practices

Best practices

  • Record ကို ရလဒ် ၂-၃ ခု ပြန်ပေးတဲ့နေရာမှာ သုံးပါ၊ typedef နဲ့ နာမည်ပေးထားရင် signature ဖတ်လို့ပိုလွယ်ပါတယ်။
  • Switch expression ထဲမှာ တိကျတဲ့ case ကို အပေါ်ထားပြီး guard ပါတာကို ပါမပါတဲ့ တူညီ pattern ရဲ့ အပေါ်ကို ထားပါ။
  • Sealed type ကို switch လုပ်ရင် _ မထည့်ပါနဲ့၊ subtype အသစ်ထပ်လာရင် compiler သတိပေးတာကို ဆက်ရချင်ရင်ပါ။
  • Primary constructor ကို သုံးမယ်ဆိုရင် team ရဲ့ SDK version ကို pubspec.yaml ရဲ့ sdk constraint မှာ ပြင်ပေးထားပါ။

Mini challenge

Mini challenge: command parser

စာလုံးစာရင်း (words) ကို list pattern နဲ့ ခွဲပြီး (command, args) record အဖြစ် ပြောင်းတဲ့ parse function နဲ့ အဲဒီ record ကို စာသားအဖြစ် ဖော်ပြတဲ့ describe function ရေးပါ။ နှစ်ခုလုံး switch expression ဖြစ်ရပါမယ်။

  • typedef Parsed = ({String command, int args}); နဲ့ parse က [], [cmd], [cmd, ...rest] ကို case သုံးခုအဖြစ် ကိုင်ရမယ်
  • describe က record pattern သုံးပြီး 'none' နဲ့ args ၂ ခုထက်များတဲ့ 'add' ကို သီးခြားပြောပြရမယ်
  • နောက်ဆုံး case တစ်ခုက ကျန်တာကို ဖမ်းပြီး switch က exhaustive ဖြစ်ရမယ်
  • Input ငါးမျိုးကို loop ပတ်ပြီး print ထုတ်ကာ နောက်ဆုံးမှာ record ကို destructure လုပ်ပြပါ
command_parser.dart
// Result of parsing a command line.
typedef Parsed = ({String command, int args});

// TODO 1: switch over `words` using list patterns
Parsed parse(List<String> words) {
  // TODO: [] -> command 'none', no args
  // TODO: [cmd] -> that command, no args
  // TODO: [cmd, ...rest] -> that command, rest.length args
  throw UnimplementedError();
}

// TODO 2: switch over the record with record patterns, most specific first
String describe(Parsed p) {
  // TODO: 'none', 'add' with 2+ args, 'add' with 1 arg, no args, anything else
  throw UnimplementedError();
}

void main() {
  // TODO 3: parse and describe five inputs (empty, one word, add x2, rm x3)
  // TODO 4: destructure one result with final (:command, :args) = ...;
}

ရလဒ်: Run လိုက်ရင် ဒီလို print ထွက်ရပါမယ်: none/0: nothing to do list/0: list with no arguments add/1: adding one item add/2: adding several items rm/3: rm with 3 arguments x 1

အရိပ်အမြွက် ကြည့်ရန်

list pattern ကို ရေးတဲ့အခါ [var cmd, ...var rest] လို့ ရေးရင် rest ထဲက ကျန် element တွေကို ရပါတယ်။ describe မှာ (command: 'add', args: >= 2) ကို (command: 'add', args: 1) ရဲ့ အပေါ်မှာ ထားပါ၊ ပြီးရင် (command: var c, args: var n) ကို နောက်ဆုံးမှာ ထားပါ။ Record destructuring အတွက် final (:command, :args) = parse([...]); လို့ ရေးပါတယ်။

အဖြေ ကြည့်ရန်
command_parser.dart
typedef Parsed = ({String command, int args});

Parsed parse(List<String> words) => switch (words) {
      [] => (command: 'none', args: 0),
      [var cmd] => (command: cmd, args: 0),
      [var cmd, ...var rest] => (command: cmd, args: rest.length),
    };

String describe(Parsed p) => switch (p) {
      (command: 'none', args: _) => 'nothing to do',
      (command: 'add', args: >= 2) => 'adding several items',
      (command: 'add', args: 1) => 'adding one item',
      (command: var c, args: 0) => '$c with no arguments',
      (command: var c, args: var n) => '$c with $n arguments',
    };

void main() {
  final inputs = <List<String>>[
    [],
    ['list'],
    ['add', 'milk'],
    ['add', 'milk', 'eggs'],
    ['rm', 'a', 'b', 'c'],
  ];
  for (final words in inputs) {
    final parsed = parse(words);
    print('${parsed.command}/${parsed.args}: ${describe(parsed)}');
  }
  final (:command, :args) = parse(['x', 'y']);
  print('$command $args');
}

Quick Quiz 1 / 3

print((x: 1, y: 2) == (y: 2, x: 1)) က ဘာ print ထုတ်မလဲ?

Quick Quiz 2 / 3

sealed class Shape ကို Circle, Rect, Tri က extends လုပ်ထားတယ်။ switch (s) { Circle() => 'c', Rect() => 'r' } ဆိုတဲ့ switch expression မှာ ဘာဖြစ်မလဲ?

Quick Quiz 3 / 3

class Point(int x, int y); ကို ကြေညာပြီး print(Point(1, 2).x) ရေးရင် ဘာကြောင့် error ရလဲ?

မှတ်ထားရမယ့် အချက်များ

  • Record က positional ဒါမှမဟုတ် named field ပါတဲ့ မပြောင်းလဲနိုင်တဲ့ value အထုပ်ငယ်ဖြစ်ပြီး field တန်ဖိုးတွေအလိုက် equal ဖြစ်ပါတယ်၊ ဖတ်ဖို့ $1 ဒါမှမဟုတ် နာမည်သုံးပါ။
  • Pattern က value ရဲ့ shape ကို စစ်ပြီး အစိတ်အပိုင်းတွေကို ချိတ်ပေးပါတယ်၊ switch expression မှာ ပထမ ကိုက်တဲ့ case က နိုင်ပြီး when guard နဲ့ အခြေအနေ ထပ်ထည့်နိုင်ပါတယ်။
  • Sealed type၊ enum ကို switch လုပ်ရင် compiler က exhaustive ဖြစ်မဖြစ် စစ်ပေးပြီး _ ထည့်ရင် အဲဒီ ကာကွယ်မှုကို ဆုံးရှုံးပါတယ်။
  • Primary constructor (class Point(final int x, final int y);) က Dart 3.13.7 မှာ flag မလိုပါဘူး၊ language version 3.13 လိုပြီး final/var ပါမှ field ဖြစ်ပါတယ်။

Dart primary constructors — Dart

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

Records, Patterns & Primary Constructors | Thuta Learning