var numbers = [1,2,3,4];
List<int> numbers2 = [1,2,3,4];
위의 두 방법 모두 'int'의 list를 만드는 방법이다.
이때, 끝을 쉼표로 마무리하면 아래와 같이 자동으로 해준다.
var numbers = [
1,
2,
3,
4,
];
List<int> numbers2 = [
1,
2,
3,
4,
];
collection if
이거는 강의를 듣자마자 진짜 엄청난 기능이라고 느꼈다.
딱 봐도, 많이 쓸 수 있을 기능일 것 같다.
var giveMeFive = true;
var numbers3 = [
1,
2,
3,
4,
if (giveMeFive) 5, //<- giveMeFive가 true라면 '5'라는 숫자 추가
];
이렇게 'giveMeFive'가 'true'이라면 숫자 '5'가 리스트에 추가된다는 의미이다. 이는 아래의 코드블럭과 동일한 의미이다.
var numbers = [
1,
2,
3,
4,
];
if (giveMeFive) {
numbers.add(5);
}
음. 신기한 기능인 collection if 까지 살펴봤다.
요즘, FRM공부를 시작해서 코드 공부할 시간을 쪼개기 힘들다.(놀 시간이 없어요.)
어떻게든 틈을 만들어서 조금씩 공부 해야지...
원래는, 여기서 끝나는 거였는데, Sets를 하면서 [1,2] == [1,2] 가 아니라는 사실을 알게 되면서 dart공식문서와 몇몇 블로그를 읽어보니 재밌는게 있었다.
void main() {
// 끝을 쉼표로 마무리하면 저절로 여러 줄로 만들어짐!
var numbers = [1,2,3,4];
var numbers2 = [1,2,3,4];
var numbers100 = [numbers, numbers2];
var numbers101 = [numbers, ...numbers2];
var numbers102 = [...numbers, ...numbers2];
print(numbers100); // Prints "[[1,2,3,4], [1,2,3,4]]"
print(numbers101); // Prints "[[1,2,3,4], 1,2,3,4]"
print(numbers102); // Prints "[1,2,3,4, 1,2,3,4]"
}
리스트 앞에 '...'을 붙이면 요소가 뙇 추가된다!
이때 '...'을 Spread Operator라고 부른다.
자세한 것은 공식 문서 : https://dart.dev/guides/language/language-tour#lists 를 참고하자.
[1,2] == [1,2] 가 왜 아닐까?
(https://dart.dev/tools/linter-rules)
Currently, the case will only match if the incoming value has the same identity as the constant. So:
test(List<int> list) {
switch (list) {
case [1, 2]: print('Matched'); break;
default: print('Did not match'); break;
}
}
main() {
test(const [1, 2]); // Prints "Matched".
test([1, 2]); // Prints "Did not match".
}
With patterns, a list or map literal becomes a list or map pattern. The pattern destructures the incoming object and matches if the subpatterns all match. In other words, list and map pattern match using something more like deep equality.
그렇다. 'const'를 이용한다면 동일한 요소의 리스트를 찾을 수 있다.
-> pattern을 사용한다고 하는데... 더 공부하기엔 시간이 없어서... 여기까지...
를 참조하자면, List는 '참조 타입(Reference Type)'으로, 리스트를 비교 할 때에는 '주소'를 이용해 비교하게 된다.
그러면 당연하게도 [1,2]의 두 리스트는 다르다.
왜? 주소가 다르잖아.
'앱 만들기 프로젝트 > Dart' 카테고리의 다른 글
Dart - 2.3 Collection For (0) | 2023.03.07 |
---|---|
Dart - 2.2 String Interpolation (0) | 2023.03.07 |
Dart - 2.0 Basic Data Types (0) | 2023.02.28 |
Dart - 1.6 Constant Variables (0) | 2023.02.28 |
Dart - 1.5 Late Variables (0) | 2023.02.28 |