dart 3.0이었나 업데이트 됬던 문법 내용으로 알고는 있었지만 제대로 정리해본 적이 없어서 개념정리 용도로 한번 정리해보려고 글을 쓰게 됬다.
Records
Records are an anonymous, immutable, aggregate type. Like other collection types, they let you bundle multiple objects into a single object. Unlike other collection types, records are fixed-sized, heterogeneous, and typed.
공홈의 소개글이다.
위의 글 내용대로 다른 컬렉션유형과 마찬가지로 여러 개체를 단일 개체로 묶을 수 있다. 차이점은 다른 컬렉션 유형과 달리 레코드는 크기가 고정되어 있고 유형이 다양하며 유형이 다르다.
var record = ('first', a: 2, b: true, 'last');
아래와 같이 리턴타입을 record로 반환하는 것도 이제 가능하다!
(int, int) swap((int, int) record) {
var (a, b) = record;
return (b, a);
}
당연히 정의도 이렇게 가능하다
// Record type annotation in a variable declaration:
(String, int) record;
// Initialize it with a record expression:
record = ('A string', 123);
// Record type annotation in a variable declaration:
({int a, bool b}) record;
// Initialize it with a record expression:
record = (a: 123, b: true);
신기한 규칙이 있었는데 ,
레코드 유형의 명명된 필드 이름은 레코드의 유형정의 또는 모양의 일부라 이름이 다르고 명명된 필드가 있는 두 레코드의 유형이 다르다.
명명된 필드가 아닌경우는 레코드의 유형에 영향을 주지 않아서 아래의 코드같은 경우는 동일하다고 인식된다.
({int a, int b}) recordAB = (a: 1, b: 2);
({int x, int y}) recordXY = (x: 3, y: 4);
recordAB = recordXY; //Error
(int a, int b) recordAB = (1, 2);
(int x, int y) recordXY = (3, 4);
recordAB = recordXY; // OK.
레코드필드
var record = ('first', a: 2, b: true, 'last');
print(record.$1); // Prints 'first'
print(record.a); // Prints 2
print(record.b); // Prints true
print(record.$2); // Prints 'last'
Pattern
Patterns are a syntactic category in the Dart language, like statements and expressions. A pattern represents the shape of a set of values that it may match against actual values.
공홈의 소개글로 요약하면 "패턴은 실제 값들과 일치할 수 있는 값 집합의 모양"을 나타낸다고 한다.
matching
const a = 'a';
const b = 'b';
switch (obj) {
// List pattern [a, b] matches obj first if obj is a list with two fields,
// then if its fields match the constant subpatterns 'a' and 'b'.
case [a, b]:
print('$a, $b');
}
Destructuring
var numList = [1, 2, 3];
// List pattern [a, b, c] destructures the three elements from numList...
var [a, b, c] = numList;
// ...and assigns them to new variables.
print(a + b + c);
구조 분해 패턴 안에는 모든 종류의 패턴을 중첩할 수 있다.
switch (list) {
case ['a' || 'b', var c]:
print(c);
}
다 적진 않았고 더 자세한 내용을 보려면 역시 공홈이 최고시다.
https://dart.dev/language/pattern-types
Pattern types
Pattern type reference in Dart.
dart.dev
두가지를 보고 느낀건 hashing을 하기에 굉장히 편할거 같아보였다. 그리고 리턴할때 값을 여러개 리턴하는건 정말 필요했었는데 드디어 개발되었구나라는 생각이 들었다. 유용하게 잘 쓸 수 있는 기능들로 보인다.
'개발 > Dart' 카테고리의 다른 글
null-aware spread operator (...?) (0) | 2023.12.31 |
---|