Develop/Flutter
다트 함수 (4)
HaeYoung_12
2024. 8. 13. 10:08
typedef와 함수
- 함수의 시그니처를 정의하는 값.
- 즉 함수 선언부를 선언부를 정의하는 키워드
- 시그니처란? 반환값타입, 매개변수의 개수와 타입
- 일반적인 변수처럼 사용함
import 'dart:io';
typedef Operation = void Function(int x, int y); //typedef는 일반적인 변수의 type처럼 사용가능
void add(int x, int y) {
print('결과값: ${x + y}');
}
void subtract(int x, int y) {
print('결과값: ${x - y}');
}
void calculate(int x, int y,Operation oper) {
oper(x,y);
}
void main() {
Operation oper = add;
oper(1, 2);
//subtract() 함수도 Operation에 해당되는
//시그니처 이므로 oper변수에 저장가능
oper = subtract;
oper(1, 2);
// 다트에서 함수는 일급객체라 함수를 값처럼 사용가능
calculate(1, 3, add);
}
Version Update
2.13 이전 버전 에서는 typedef를 함수 타입에만 사용이 가능했지만, 새로운 버전은 여러 타입을 참조 가능하다
typedef ListMapper<X> = Map<X, List<X>>;
Map<String, List<String>> m1 = {}; // typedef를 사용하지 않았을때, 타입 선언이 장황합니다.
ListMapper<String> m2 = {}; // 위와 같지만 더 깔끔하고 짧습니다.
try...catch
- 특정 코드의 실행을 시도(try) 해보고 문제가 있으면 에러를 잡으라는(catch)뜻.
throw
- 키워드를 사용 에러를 발생시킬수 있음.
import 'dart:io';
void main() {
//try..catch
try{
//에러가 없을때 실행할 로직
final String name='코드팩토리';
print(name);
}catch(e){
//에러가 있을때 실행할로직
print(e);
}
// throw 키워드-> 고의적으로 에러를 발생시킴
try{
final name2='코도도';
throw Exception('이름이 잘못됬습니다!');
print(name2);
}catch(e){
print(e);
}
}