반응형
function
함수정의하기
// void 뭔가를 return 하지 않는 함수
void sayHello(String name) {
print("Hello $name, nice to meet you");
}
// string을 return하는 함수로 설정
String sayHello2(String name) {
return "Hello $name, nice to meet you";
}
// fat arrow syntax
String sayHello3(String name) => "Hello $name, nice to meet you";
void main() {
print(sayHello2('siha')); // Hello siha, nice to meet you
print(sayHello3('siha')); // Hello siha, nice to meet you
}
named parameter
// named parameter 지원하지 않는 일반 function
String sayHello(String name, int age, String country) {
return "Hello $name, you are $age, and you come from $country";
}
// named parameter 지원하는 함수 정의하기
String sayHello2({String name, int age, String country}) {
return "Hello $name, you are $age, and you come from $country";
// parameter가 null 일 경우 어떻게 할건지? 에 대하여 Dart가 경고하게됨
// 방법 1 -> named argument에 default value 정하기
// {String name = "anon", int age = 19, String country = 'seoul'}
// 방법 2 -> required modifier 이용하여 꼭 필요하다고 명시
// String sayHello2({
// required String name,
// required int age,
// required String country,
// }) { ... }
}
void main() {
print(sayHello('siha', 7, 'seoul')); // 순서도 헷갈릴 수 있고 직관적으로 딱 알아보기 어렵
// named parameter 사용
// 순서와 상관없이 자료형만 맞춰주면 됨
print(sayHello2(
age: 10,
name: 'momo',
country: 'seoul',
));
}
optional positional parameter
많이 쓰지는 않지만 구조 알아놓기
[타입? 변수 = 기본값]
// optional positional parameter
String sayHello(String name, int age, [String? country = 'seoul']) =>
'Hello $name, you are $age years old from $country';
void main() {
var results = sayHello('siha', 12);
print(results); // Hello siha, you are 12 years old from seoul
}
반응형
'앱 > Dart' 카테고리의 다른 글
Dart Named Countructor Parameter 사용예제(+ 클래스 초기화 문법) (0) | 2023.01.22 |
---|---|
Dart Class, constructors 기본 예제 (0) | 2023.01.21 |
Dart QQ operator, QQ assignment operation (0) | 2023.01.20 |
Dart의 Data Types(list, collection if, collection for, Maps, List, Set) (0) | 2023.01.17 |
Dart 기본 개념 및 변수(+Dynamic Type, null safety, final, late, const) (0) | 2023.01.16 |