본문 바로가기

Flutter

[flutter] typedef 왜 쓰는지 이유/사용하는 방법/간단한 예제코드

반응형

안녕하세요? 오늘은 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

 

 

 

반응형