developer tip

Dart에서 명명 된 매개 변수와 위치 매개 변수의 차이점은 무엇입니까?

optionbox 2020. 8. 30. 08:12
반응형

Dart에서 명명 된 매개 변수와 위치 매개 변수의 차이점은 무엇입니까?


Dart는 명명 된 선택적 매개 변수와 위치 선택적 매개 변수를 모두 지원합니다. 둘의 차이점은 무엇입니까?

또한 선택적 매개 변수가 실제로 지정되었는지 어떻게 알 수 있습니까?


Dart에는 namedpositional 의 두 가지 유형의 선택적 매개 변수가 있습니다. 차이점을 논의하기 전에 먼저 유사점에 대해 논의하겠습니다.

Dart의 선택적 매개 변수는 호출자가 함수를 호출 할 때 매개 변수에 대한 값을 지정할 필요가 없다는 점에서 선택 사항 입니다.

선택적 매개 변수는 필수 매개 변수 다음에 선언 할 수 있습니다.

선택적 매개 변수는 호출자가 값을 지정하지 않을 때 사용되는 기본값을 가질 수 있습니다.

위치 선택적 매개 변수

로 래핑 된 매개 변수 [ ]는 위치 선택적 매개 변수입니다. 다음은 예입니다.

getHttpUrl(String server, String path, [int port=80]) {
  // ...
}

위의 코드에서는 port선택 사항이며 기본값은 80입니다.

getHttpUrl세 번째 매개 변수를 사용하거나 사용하지 않고 호출 할 수 있습니다 .

getHttpUrl('example.com', '/index.html', 8080); // port == 8080
getHttpUrl('example.com', '/index.html');       // port == 80

함수에 대해 여러 위치 매개 변수를 지정할 수 있습니다.

getHttpUrl(String server, String path, [int port=80, int numRetries=3]) {
  // ...
}

선택적 매개 변수는 지정하려는 경우 생략 할 수없는 위치 에 있습니다 .portnumRetries

getHttpUrl('example.com', '/index.html');
getHttpUrl('example.com', '/index.html', 8080);
getHttpUrl('example.com', '/index.html', 8080, 5);

물론 8080과 5가 무엇인지 알지 못한다면 매직 넘버가 무엇인지 알기 어렵습니다. 명명 된 선택적 매개 변수 를 사용하여 더 읽기 쉬운 API를 만들 수 있습니다 .

명명 된 선택적 매개 변수

로 래핑 된 매개 변수 { }는 명명 된 선택적 매개 변수입니다. 다음은 예입니다.

getHttpUrl(String server, String path, {int port = 80}) {
  // ...
}

getHttpUrl세 번째 매개 변수를 사용하거나 사용하지 않고 호출 할 수 있습니다 . 당신은 해야한다 함수를 호출 할 때 매개 변수 이름을 사용합니다.

getHttpUrl('example.com', '/index.html', port: 8080); // port == 8080
getHttpUrl('example.com', '/index.html');             // port == 80

함수에 대해 여러 개의 명명 된 매개 변수를 지정할 수 있습니다.

getHttpUrl(String server, String path, {int port = 80, int numRetries = 3}) {
  // ...
}

명명 된 매개 변수는 이름으로 참조되기 때문에 선언과 다른 순서로 사용할 수 있습니다.

getHttpUrl('example.com', '/index.html');
getHttpUrl('example.com', '/index.html', port: 8080);
getHttpUrl('example.com', '/index.html', port: 8080, numRetries: 5);
getHttpUrl('example.com', '/index.html', numRetries: 5, port: 8080);
getHttpUrl('example.com', '/index.html', numRetries: 5);

특히 부울 플래그 나 문맥에 맞지 않는 번호가있을 때 이름이 지정된 매개 변수가 호출 사이트를 이해하기 쉽게 만든다고 생각합니다.

선택적 매개 변수가 제공되었는지 확인

안타깝게도 "선택적 매개 변수가 제공되지 않음"과 "선택적 매개 변수가 기본값으로 제공됨"사례를 구분할 수 없습니다.

Note: You may use positional optional parameters or named optional parameters, but not both in the same function or method. The following is not allowed.

thisFunctionWontWork(String foo, [String positonal], {String named}) {
  // will not work!
}

In Dart with my understanding, method parameter can be given in two type.

  • Required parameter
  • Optional parameter (positional, named & default)

>> Required Parameter

Required parameter is a well know old style parameter which we all familiar with it

example:

findVolume(int length, int breath, int height) {
 print('length = $length, breath = $breath, height = $height');
}

findVolume(10,20,30);

output:

length = 10, breath = 20, height = 30

>> Optional Positional Parameter

parameter will be disclosed with square bracket [ ] & square bracketed parameter are optional.

example:

findVolume(int length, int breath, [int height]) {
 print('length = $length, breath = $breath, height = $height');
}

findVolume(10,20,30);//valid
findVolume(10,20);//also valid

output:

length = 10, breath = 20, height = 30
length = 10, breath = 20, height = null // no value passed so height is null

>> Optional Named Parameter

  • parameter will be disclosed with curly bracket { }
  • curly bracketed parameter are optional.
  • have to use parameter name to assign a value which separated with colan :
  • in curly bracketed parameter order does not matter
  • these type parameter help us to avoid confusion while passing value for a function which has many parameter.

example:

findVolume(int length, int breath, {int height}) {
 print('length = $length, breath = $breath, height = $height');
}

findVolume(10,20,height:30);//valid & we can see the parameter name is mentioned here.
findVolume(10,20);//also valid

output:

length = 10, breath = 20, height = 30
length = 10, breath = 20, height = null

>> Optional Default Parameter

  • same like optional named parameter in addition we can assign default value for this parameter.
  • which means no value is passed this default value will be taken.

example:

findVolume(int length, int breath, {int height=10}) {
 print('length = $length, breath = $breath, height = $height');
} 

findVolume(10,20,height:30);//valid
findVolume(10,20);//valid 

output:

length = 10, breath = 20, height = 30
length = 10, breath = 20, height = 10 // default value 10 is taken

thanks for the clear explanation given from this video link, credits to the video creator.

video link : OptionalPositionalParameters

video link : OptionalNamedParameters

video link : OptionalDefaultParameters


When the parameter of a function is specified using "paramName : value" syntax, then it is a named parameter. Such parameters can be rendered optional by enclosing them between [ and ] brackets. A rudimentary demonstration of this function can be demonstrated in the following Hello World program:

sayHello([String name = ' World!']) {
  print('Hello, ${name}');
}

void main() {
  sayHello('Govind');
}

From doc we get that both positional and named parameters are optional, which means they all can be absent.

In my opinion, named parameters are more strict than positional ones. For example, if you declare such a method:

String say({String from, String msg})

Above from and msg are named parameters, when you call method say you must use say(from: "xx", msg: "xx"). The keys cannot be absent.

However if you use positional parameters, you are free.

참고URL : https://stackoverflow.com/questions/13264230/what-is-the-difference-between-named-and-positional-parameters-in-dart

반응형