본문 바로가기

[Flutter] 문법정리#2 함수, 람다, typedef

I'm 영서 2023. 1. 12.
반응형

Dart 에서는 매개변수를 지정하는 방법으로 순서가 고정된 매개변수(positional parameter)와 이름이 있는 매개변수 (named parameter)가 있다.

일반 함수

int positionalAdd(int a , int b){
return a+b
}

int namedAdd({required int a , requried int b}){
 return a+b
}

positionalAdd(10,20)

namedAdd(a : 30 , b :20)

int combineAdd1(int a, [int b = 2]){
	return a + b;
}

int combineAdd2({required int a, int b=2})
{
	return a + b;
}

int combineAdd3( int a, {required int b, omt c =4,})
{
	return a + b + c
}

 

고정된 매개변수와 이름이 있는 매개변수를 혼용할 수 있다.

 

 

람다

 

일반적인 익명함수에서 {}를 뱨고 => 기호를 추가한것이 람다함수

 

.reduce를 활용하여 익명함수와 람다함수를 구현하면다음과 같다.

List<int> numbers =[1,2,3,4,5,6]

//일반적인 익명함수
var tot = numbers.reduce( (value, element) {
	return value + element
};

//람다함수
tot = numbers.reduce( (value, element) => value + element );

 

typedef

함수의 시그니처를 정의하는 값.  여기서 시그처는 반환값 타입, 매개변수 개수와 타입등을 말한다. (함수 선언부) 

typedef Operation = void Funection(int x, int y);

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);
    oper = subtract;
    oper(1, 2)
    
    calculate(11, 22, add)
}
반응형

댓글