Record in Dart
Record ဆိုတာကတော့ Dart ရဲ့ built-in data structure တွေထဲက တခုပဲ ဖြစ်ပြီး Dart version 3.0 ကစပြီး ပါဝင်လာတာ ဖြစ်ပါတယ်။
သူ့ကို အသုံးပြုချင်းအားဖြင့် တခုထက်ပိုတဲ့ object တွေကို class အသစ်တွေဆောက်ဖို့မလိုဘဲ တခုတစည်းထဲ စုပေါင်းလို့ရသွားပါတယ်။ သူ့ကိုသုံးပြီး စုတဲ့အခါ type checking ပါတဲ့အတွက် record type အပြောင်းအလဲ ဖြစ်တဲ့အခါ အသုံးပြုတဲ့ နေရမှာ သက်ရောက်မှု ရှိမရှိ မြန်မြန်ဆန်ဆန် သိနိုင်ပါတယ်။ ပြီးတော့ record တွေဟာ immutable ဖြစ်တဲ့အတွက် value တွေ function တခုက တခု ပို့တဲ့အချိန်မှာ အပြောင်းအလဲ လုပ်မိမှာကို ပူဖို့မလိုတော့ပါဘူး။
ဘယ်လိုနေရာမှာ အသုံးများသလဲဆို ကျွန်တော်တို့ function တွေကနေ တခုထက်ပိုတဲ့ value တွေကို return ပြန်ရတဲ့အခါ class အသစ်တွေ ထပ်ဆောက်ပြီးတော့ return မပြန်တော့ဘဲ record အနေနဲ့ပဲ return ပြန်သွားလို့ ရပါတယ်။
Syntax
Record syntax က python ရဲ့ tuple နဲ့တော်တော်လေး ဆင်ပါတယ်။ ( ) ကို အသုံးပြုပြီးတော့ record type ကို တည်ဆောက်တာ ဖြစ်ပါတယ်။
var person = ("Peter", 23, true);ဒီဥပမာမှာဆိုရင် person က record data type ပဲ ဖြစ်ပါတယ်။ Peter, 23, true ဆိုတဲ့ value ၃ခုပါဝင်တဲ့ record ဖြစ်ပါတယ်။ value တွေကို access လုပ်ဖို့လိုတဲ့အခါ person.$1, person.$2, person.$3 ဆိုပြီး နေရာအလိုက် access လုပ်သွားလို့ရပါတယ်။
print(person.$1); // Peter
print(person.$2); // 23
print(person.$3); // truevalue တွေကို $1 $2 အဲ့လိုတွေ အသုံးမပြုချင်တဲ့အခါ named field တွေထည့်ပေးလိုက်လို့ရပါတယ်။ named field တွေ ထည့်လိုက်ချင်းအားဖြင့် value တွေရဲ့ အဓိပ္ပါယ် ပိုပြီး ပေါ်လွင်သွားပါလိမ့်မယ်။ အခုလို ဖြစ်သွားပါလိမ့်မယ်။
({String name, int age, bool isSingle}) person = (
name: "Peter",
age: 23,
isSingle: true,
);print(person.name); // Peter
print(person.age); // 23
print(person.isSingle); // trueUsage
Record တွေ သုံးလို့အကောင်းဆုံးနေရာကတော့ function တွေခေါ်တဲ့အချိန်နဲ့ data တွေကို DTO (Data Transfer Object) လိုမျိုး အသုံးပြုတာတွေမှာ အရမ်းပဲ အသုံးဝင်ပါတယ်။
(int, int) swap((int, int) record) {
var (a, b) = record;
return (b, a);
}ဒါကတော့ dart language documentation မှာ ပေးထားတဲ့ ဥပမာဖြစ်ပြီးတော့ အသုံးပြုဖို့ သင့်တော်တဲ့ အခြေအနေတွေကို ပြပေးထားတာပဲ ဖြစ်ပါတယ်။ Record ကို function parameter, return annotation, record to record change လုပ်တာတွေမှာ အသုံးပြုထားတာပဲ ဖြစ်ပါတယ်။
ပုံမှန်အသုံးပြုကြတဲ့အတိုင်းဆို ကျွန်တော်တို့ return လုပ်တဲ့နေရာမှာ value တခုထက်ပိုပြီးတော့ ပြန်ချင်တယ်ဆို class တွေကို တည်ဆောက်ပြီးတော့ ပြန်ကြလေ့ရှိပါတယ်။ class နဲ့ဆို ဘယ် field တွေပါလဲ အလွယ်တကူ သိနိုင်ပြီးတော့ development လုပ်တဲ့အချိန်မှာထဲက မှားတာတွေ ရှိတယ်ဆိုလဲ အလွယ်တကူ သိနိုင်တာကြောင့်ပဲ ဖြစ်ပါတယ်။ အခုတော့ class တွေကို ဒီလိုနေရာတခုထဲအတွက်ဆိုပြီး တည်ဆောက်နေစရာမလိုတော့ပါဘူး။ record နဲ့ ပြန်လိုက်ချင်းအားဖြင့် class လိုမျိုး ပါဝင်တဲ့ feild တွေကို အလွယ်တကူ သိနိုင်ပြီးတော့ class အပိုတွေလဲ ရှုပ်မနေတော့ပါဘူး။