Dart

Constructor - 상수생성자

Michelle Hwang 2021. 3. 27. 18:09

1) 기본 생성자 (Default constructor)

2) 이름 있는 생성자 (Named constructor)

3) 초기화 리스트 (Initializer list)

4) 리다이렉팅 생성자 (Redirecting constructor)

5) 상수 생성자 (Constant constructor)

6) 팩토리 생성자 (Factory constructor)

 

상수 생성자는 말 그대로 생성자를 상수처럼 만들어 준다. 

이 말은 해당 클래스가 상수처럼 변하지 않는 객체를 생성한다는 것이다. 

상수 생성자를 만들기 위해서는 인스턴스 변수가 모두 final이어야 한다. 

또한 생성자는 const 키워드가 붙어야 한다. 

 

예제1)

class ImmutablePoint {
  static const ImmutablePoint origin = ImmutablePoint(0, 0);

  final double x, y;

  const ImmutablePoint(this.x, this.y);
}

예제2)

void main() {
  Person person1 = const Person('Hwang', 20);
  Person person2 = const Person('Hwang', 20);
  Person person3 = new Person('Hwang', 20);
  Person person4 = new Person('Hwang', 20);

  print(identical(person1, person2));
  print(identical(person2, person3));
  print(identical(person3, person4));
}

class Person {
  final String name;
  final int age;

  const Person(this.name, this.age);
}

* 결과

true
false
false