반응형
안녕하세요? 오늘은 dart에서 typedef 키워드를 사용하는 방법을 알아볼게요
typedef: 함수를 변수, 필드로 사용하기 위해 형식을 정의하는 키워드라고 보시면 됩니다.
typedef를 사용하는 이유는 자료형을 재정의해서 코드의 가독성을 높여준다는 장점이 있습니다.
사용하는 방법은 간단합니다.
1.typedef에 사용할 함수와 typedef의 타입을 맞춰서 선언해줍니다.
typedef Operation(int a, int b);
void add(int a, int b){
int result=a+b;
print('add $a+$b=$result');
}
void subtract(int a, int b){
int result=a-b;
print('subtract $a-$b=$result');
}
2.사용하기 전 typeDef를 선언해 사용할 함수를 할당해주고 파라미터값을 넣어주면 됩니다.
Operation operation=add;
operation(1,2);
3.재정의가 가능하기 때문에 같은 type이라면 계속 값을 바꿔줄 수 있습니다.
operation=subtract;
operation(10,1);
4.전체코드입니다.
void main() {
Operation operation=add;
operation(1,2);
operation=subtract;
operation(10,1);
operation=multiply;
operation(5,5);
operation=divide;
operation(10,2);
}
typedef Operation(int a, int b);
void add(int a, int b){
int result=a+b;
print('add $a+$b=$result');
}
void subtract(int a, int b){
int result=a-b;
print('subtract $a-$b=$result');
}
void multiply(int a, int b){
int result=a*b;
print('multiply $a*$b=$result');
}
void divide(int a, int b){
int result=a~/b;
print('divide $a~/$b=$result');
}
//출력
add 1+2=3
subtract 10-1=9
multiply 5*5=25
divide 10~/2=5
반응형
'Flutter' 카테고리의 다른 글
| [flutter] iphone App 클론코딩하기1편 스톱워치StopWatch 구현 (2) | 2023.04.10 |
|---|---|
| [flutter]EventBus 개념 | 특징 | 사용방법 알아보기 (0) | 2023.04.04 |
| 안드로이드스튜디오에서 sqlite database 확인하기 (+database inspector가 안보일 때 찾는 방법) (0) | 2023.01.31 |
| [flutter] stream과 streambuilder의 간단하게 요약정리 (0) | 2023.01.27 |
| [flutter] flutter앱에 cloud_firestore 연결 / 예제코드 (0) | 2023.01.25 |