[Grammar] Cascade Notations

zinnnn37·2024년 5월 15일
0

🎯 Flutter

목록 보기
2/8

🎶 What is Cascade Notations?

📍 ..: 하나의 객체에서 여러번의 메소드 호출, 멤버변수 접근 등을 가능하게 하는 연산자
📍 필요 없는 변수 선언을 줄일 수 있다

// without cascade notation
var paint = Paint();
paint.color = Colors.black;
paint.strokeCap = StrokeCap.round;
paint.strokeWidth = 5.0;

// with cascade notation
var paint = Paint()
  ..color = Colors.black
  ..strokeCap = StrokeCap.round
  ..strokeWidth = 5.0;

📍 중첩도 가능하다

final addressBook = (AddressBookBuilder()
	  // AddressBookBuilder()의 반환값을 찹조
      ..name = 'jenny'
      ..email = 'jenny@example.com'
      ..phone = (PhoneNumberBuilder()
      	    // PhoneNumberBuilder()의 반환값을 참조
            ..number = '415-555-0100'
            ..label = 'home')
          .build())
    .build();

메소드를 사용하는 경우 호출된 메소드 다음의 cascade notation은 호출된 메소드의 리턴값을 참조한다


⚠️ 주의할 점

  1. nullable한 객체를 참조한다면 ?..로 시작해야 한다.
    → 만약null인 객체를 참조한다면 이하의 연산은 실행되지 않는다.
// without cascade notation
var button = querySelector('#confirm');
button?.text = 'Confirm';
button?.classes.add('important');
button?.onClick.listen((e) => window.alert('Confirmed!'));
button?.scrollIntoView();

// with cascade notation
querySelector('#confirm') // Get an object.
  ?..text = 'Confirm' // Use its members.
  ..classes.add('important')
  ..onClick.listen((e) => window.alert('Confirmed!'))
  ..scrollIntoView();
  1. 반환값이 없는 메소드를 사용하는 경우 에러가 발생한다
    → 없는 반환값을 참조하려 하기 때문
var sb = StringBuffer();
sb.write('foo')
  ..write('bar'); // Error: method 'write' isn't defined for 'void'.

🍃 Spread operators

📍 ...: 여러개의 항목을 collections에 간편하게 추가할 수 있도록 한다
📍 연산자가 아니므로 우선순위가 존재하지 않는다!
📍 nullable을 포함하는 경우 ...?로 표현 가능하다

var list = [1, 2, 3];
var list2 = [0, ...list];
assert(list2.length == 4);
// res: [1, 2, 3, 4]

// nullable
var list2 = [0, ...?list];
assert(list2.length == 1);
// suppose uri.queryParameters is { 'search': 'flutter', 'page': '2' }
var params = {
  'userId': 123,
  'timeout': 300,
};

params.addAll(uri.queryParameters);

// with cascade notations
var params = {
  'userId': 123,
  'timeout': 300,
}..addAll(uri.queryParameters);
// addAll을 이용해 params에
// uri.queryParameters의 내용을 넣는다

// with spread operators
var params = {
  'userId': 123,
  'timeout': 300,
  ...uri.queryParameters
};
// spread operators를 이용해 params 내부에서 바로
// uri.queryParameters의 내용을 분해해서 넣는다

// 모두 같은 params 결과값을 가진다
{
  'userId': 123,
  'timeout': 300,
  'search': 'flutter',
  'page': '2',
}

📝 Reference

Cascade notation 관련 Dart 공식 문서
Spread operators 관련 Dart 공식 문서
Spread operators 관련 Dart github Readme

profile
😎노션 상주 중,,😎

0개의 댓글