본문 바로가기
Flutter

[flutter/dart] 클래스 생성자에 final 상수를 넣을 수 없는 이유?

by somarok 2024. 3. 8.

아래와 같이 클래스를 만들면서 상수를 생성자에 넣는 경우가 생길 수 있다.

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

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

 

그런데 final로 선언한 상수도 되지 않을까? 하고 생성자 파라미터에 넣어봤더니

class Cleric { 
  // 이렇게도 상수를 만들 수 있다.
  static final int maxHp = 50;
  static final int maxMp = 10; 
  String name;
  int hp;
  int mp;

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

 

오류가 발생했다. 왜일까?

 

같은 상수인데 생성자에 static final을 넣을 수 없는 이유는,

final은 런타임에서 읽히고, 생성자는 컴파일 타임에서 먼저 읽기 때문에 동일하게 런타임에서 읽히는 const 상수를 써줘야 한다.

 

런타임과 컴파일 타임에 대한 설명은 이전에 썼던 글 링크로 대체하겠다.

> 런타임과 컴파일 타임에 대해 알아보기