-
Dart는 오버로딩을 지원하지 않는다.Memo/Dart & Flutter 2024. 1. 3. 21:10
생성자를 생성할 때, 동일한 메소드을 타입 또는 매개변수의 개수를 다르게 하여 여러 생성자를 생성할 수 있다.
이를 '오버로딩' 이라고 한다.
그런데 Dart를 공부하면서 Dart 언어는 '오버로딩'을 지원하지 않는다는 것을 알게되었다.
Dart는 다른 언어와 다르게 타입 도는 매개변수의 개수가 다르더라도 동일한 이름을 가진 생성자를 하나만 가질 수 있다.
그 이유를 알아보니, Dart언어 만의 특성인 'Named Constructors'이 존재하였다.
✅ Named Constructors
이름을 가진 생성자는 생성자에 이름을 부여하여 다른 기능을 수행하게 할 수 있다.
즉, 이름을 다르게 하여 여러 개의 생성자를 생성할 수 있다.
class Player { String name; String team; int age; int xp; Player.blueTeam(String name, int age) : this.name = name, this.team = 'blue', this.age = age, this.xp = 0, Player.redTeam(String name, int age, int xp) : this.name = name, this.team = 'red', this.age = age, this.xp = xp; } void main() { Player.blueTeam("john", 20); Player.redTeam("james", 18, 100); }
위 코드와 같이 'blueTeam', 'redTeam' 이름을 가진 두 개의 Player 클래스 생성자를 생성하였다.
이 처럼 생성자에 각각의 이름을 부여하여 다른 기능을 수행하게 할 수 있다.
오버로딩을 대체할 또 다른 방법으로는 'Optional positional parameters'를 이용하는 것이다.
✅ Optional positional parameters
이 방법은 매게변수의 개수를 다르게 하였을 때의 생성자와 가장 유사한 방법이다.
String sayHello(String name, int age, [String? country = 'Korea']) { return "Hello $name you are $age and you from $country"; } void main() { print(sayHello('john', 20)); // "Hello john you are 20 and you from Korea" print(sayHello('james', 18, 'Canada')); // "Hello james you are 18 and you from Canada" }
위 코드와 같이 메소드의 매개변수에 대괄호( [ ] )를 이용하면 선택적 매개변수를 만들 수 있다.
즉, 대괄호로 감싼 매개변수는 옵션으로 넣어도 되고, 넣지 않아도 된다.
다만 옵션 매개변수는 값을 할당하지 않았을 때를 대비하여 deafult 값 설정이 필수적이다.
위 두 가지 방법을 이용해 다른 언어들의 오버로딩 기능을 대체할 수 있다.
Constructors
Everything about using constructors in Dart.
dart.dev
Functions
Everything about functions in Dart.
dart.dev
Function overloading in Dart
The following code: class Tools { static int roll(int min, int max) { // IMPLEMENTATION } static int roll(List<int> pair) { // IMPLEMENTATION } } renders a The name 'roll' is
stackoverflow.com
'Memo > Dart & Flutter' 카테고리의 다른 글
[Flutter] Stateless Widget과 Stateful Widget (0) 2024.01.09 [Flutter] VSCode 'The Flutter Daemon failed to start' 오류 해결 (2) 2024.01.06 [Dart] Object와 dynamic 차이 (1) 2024.01.04 [Dart] Python의 f-string과 유사한 String Interpolation (0) 2024.01.01 Dart의 컴파일 방식 - AOT, JIT, (0) 2024.01.01