반응형
// 3.2는 recap으로 복습이었다. 넘어가자!
positional parameter인 상태로도 변수를 optional하게 받을 수 있도록 할 수 있다.
* return값이 바로 나올 경우 fat arrow로 대체할 수 있다는 것을 3.0에서 배웠다.
// 일반적인 함수 선언 방식
String sayHello(String name, int age, String country) => "Hello $name, you are $age, and you come from $country";
이 함수는 무조건 'name, age, country'순서로 모든 변수를 입력해야 함수를 실행할 수 있다.
이때, 'country'는 optional하게(필수적이지 않도록)하고 싶다면?
- 대괄호를 씌워준다.
- ?를 붙여서 nullable하게 만든다.
- default value를 설정한다.
이렇게 하면.. 함수가 이렇게 변한다:
String sayHello(String name, int age, [String? country = 'korea']) => "Hello $name, you are $age, and you come from $country";
이렇게 선언하면 다음과 같이 country를 넣지 않아도 정상적으로 함수를 호출할 수 있다.
void main() {
var results = sayHello('me', 25);
print(results);
// 결과: Hello me, you are 25, and you come from korea
}
반응형
'앱 만들기 프로젝트 > Dart' 카테고리의 다른 글
Dart - 3.5 Typedef (0) | 2024.10.16 |
---|---|
Dart - 3.4 QQ Operator(Null-aware operator) (0) | 2024.10.15 |
Dart - 3.1 Named Parameters (1) | 2024.10.14 |
Dart - 3.0 Defining a Function (0) | 2024.10.14 |
Dart - 2.5 Sets (0) | 2023.03.07 |