Spread Operator (…)

테디준·2022년 11월 8일
0

List, Map, Sets 같은 collection에 여러가지 값을 넣을 때 사용한다.

1. List에서 사용 예제

void main() {
  
   // initialise a List l1
   List? l1 = ["Geeks","For","Geeks"];
    
  // initialize another List l2 using l1
  List? l2=["Wow",...l1,"is","amazing"];
  
   // print List l2
   print(l2);
}

출력값
[Wow, Geeks, For, Geeks, is, amazing]

2. Map에서 사용 예제

void main() {
    
   // initialise a Map m1
   Map? m1 = {"name":"John","age":21};
    
  // initialize another Map m2 using m1
  Map? m2={"roll no":45,"class":12,...m1};
  
   // print Map m2
   print(m2);
}

출력값
{roll no: 45, class: 12, name: John, age: 21}

3. Sets에서 사용 예제

void main() {
    
  // first set s1  
  Set<int> s1 = {5, 4, 3};
  
  // second set s2
  Set<int> s2 = {3, 2, 1};
  
  // result Set
  Set<int> result = {...s1, ...s2};
  
  // print result set
  print(result);
}

출력값
{5,4,3,2,1}

4. cascade notation(..)

.. 을 사용하면 하나의 오브젝트에 함수호출, 필드접근을 순차적으로 수행할 수 있다.이 과정 중간에 어떤 값이 반환되더라도 무시된다.

strokePaint = Paint()
      ..color = color
      ..style = PaintingStyle.stroke
      ..strokeWidth = 3
      ..strokeCap = StrokeCap.round;

위의 함수는 아래와 같은 걸 계속 반복해서 쓰므로 생략한 것이다.

strokePaint = Paint()
      strokePaint.color = color
      strokePaint.style = PaintingStyle.stroke
      strokePaint.strokeWidth = 3
      strokePaint.strokeCap = StrokeCap.round;

.. 은 중첩도 가능하다. 주의할점은 실제 오브젝트를 반환하는 함수에 .. 를 사용해야한다.

0개의 댓글