728x90

Dart 에 cascade notation(.., ?..) 이 있다.

처음 접하다보니 이게 뭔가 싶어서 찾아보고 적어둔다.

 

아래 예제의 출처는 https://www.educative.io/answers/what-is-dart-cascade-notation  인데, 약간 주석 내용을 포함해서 조금 더 보완했다.

 

class Example{
  var a;
  var b;
 
  void bSetter(b) {
    this.b = b;
  }
 
  void printValues(){
    print(this.a);
    print(this.b);
  }
}
 
void main() {
  //Instantiating two Example objects
  Example eg1 = new Example(); // 변수는 참조(메모리주소)를 저장한다.
  Example eg2 = new Example();
 
  //Using the .. operator for operations on Example object
  print("Example 1 results:");
  eg1
    ..a = 88
    ..bSetter(53)
    ..printValues();
 
  //The same operations as above but without the .. operator
  print("Example 2 results:");
  eg2.a = 88;
  eg2.bSetter(53);
  eg2.printValues();
 
  // 위 2개는 출력된 결과는 동일하다.
 
  print(eg1 == eg2); // false (메모리 주소 비교했는데 메모리 주소가 다르다.)
  /***
   * 배열은 가변 객체(Mutable Object), Custom Class 도 가변 객체
   * 객체 생성시, 가변 객체는 항상 새로운 메모리를 할당하고,
   * 불변 객체(Immutable Object)는 값이 동일하다면 기존에 생성한 객체를 재활용한다.
   * 불변 객체로 String, int, double, bool, const로 선언된 객체 등이 있다.
   * const는 컴파일 타임에 고정 값인 객체 앞에만 선언할 수 있다.
   * 컴파일 타임 : 앱 실행 전 소스코드를 기계어로 변환하는 시점
   */
}

 

cascade notation(.., ?..) 을 사용하면 같은 객체에 대해 일련의 작업을 수행할 수 있다. 

인스턴스 멤버에 접근하는 것 외에도 같은 객체에서 인스턴스 메서드를 호출할 수도 있다. 

이렇게 하면 임시 변수를 만드는 단계가 줄어들고 더 유동적인 코드를 작성할 수 있다.

 

 
  final fruits = Fruits();
 
  fruits.insert('사과');
  fruits.insert('수박');
  fruits.insert('오이');
  fruits.insert('참외');
  fruits.insert('딸기');
  fruits.insert('배');
  fruits.insert('감');
 
  // 아래와 같이 캐스케이드 연산자를 사용해서 값을 추가할 수도 있다.
  Fruits()
    ..insert('사과')
    ..insert('수박')
    ..insert('오이')
    ..insert('참외')
    ..insert('딸기')
    ..insert('배')
    ..insert('감');

 

하지만 위의 예시는 잘못된 결과가 반환된다.

왜? Custom Class 객체를 생성할 때마다 메모리 주소가 다르기 때문이다.

 

  fruits
    ..insert('사과')
    ..insert('수박')
    ..insert('오이')
    ..insert('참외')
    ..insert('딸기')
    ..insert('배')
    ..insert('감');

 

위와 같이 해야 정상적인 결과를 반환한다.

'Flutter 앱 > Dart 언어' 카테고리의 다른 글

Dart 얕은 복사(shallow copy), 깊은 복사(deep copy)  (0) 2024.01.17
Dart 값 비교 - Equatable 패키지  (0) 2024.01.17
Dart List.where  (0) 2024.01.16
[Dart 고급] Dart asMap, entries  (0) 2024.01.16
Dart fold 함수  (2) 2023.12.15
블로그 이미지

Link2Me

,