constructor

Gmini.Y·2023년 12월 1일

Dart 기본

목록 보기
4/4

Class 는 하나 이상의 Constructor를 갖으며 아래와 같은 방식으로 사용한다.

1. Constructor with positional arguments

class Cleric {
  static const int maxHp = 50;
  static const int maxMp = 10;
  int hp;
  int mp;
  String name;

  Cleric(this.name, this.hp, this.mp);
}

void main() {
  Cleric cleric = Cleric("gmin", 50, 10);
}

class 에서 선언한 변수에 constructor paremeter 값이 들어간다.

2. Constructor with named parameters

class Cleric {
  static const int maxHp = 50;
  static const int maxMp = 10;
  int hp;
  int mp;
  String name;

  Cleric(
    this.name, {
    this.hp = maxHp,
    this.mp = maxMp,
  })
}

void main() {
  Cleric cleric = Cleric("gmin", hp: 30, mp: 4);
}

위와 같은 문법으로 paremeter의 이름을 사용해서 값을 넣어줄 수 있다. 이때는 default 값도 함께 선언할수 있다. non-nullable paremeter면서 default를 선언하지 않을때는 required 키워드를 넣어주어야 한다.

3. Mixed

class Cleric {
  static const int maxHp = 50;
  static const int maxMp = 10;
  int hp;
  int mp;
  String name;

  Cleric(
    this.name, {
    this.hp = maxHp,
    this.mp = maxMp,
  }) {
    if (hp > maxHp) {
      hp = maxHp;
    }

    if (mp > maxMp) {
      mp = maxMp;
    }
  }
}

필요시 위와 같이 constructor 함수를 사용할수 있다.

0개의 댓글