prefer_const_constructors_in_immutables 진단: @immutable 클래스의 생성자는 const로 선언할 때

prefer_const_constructors_in_immutables 진단: @immutable 클래스의 생성자는 const로 선언할 때

@immutable 애너테이션이 붙은 클래스에서 const가 아닌 생성자를 발견하면 Dart 분석기가 알려주는 린트(lint) 진단이에요. 불변(immutable)이라고 밝힌 클래스의 생성자는 const로 선언해 두는 게 자연스러워요.

출처: prefer_const_constructors_in_immutables

본문

설명

분석기는 @immutable 애너테이션이 있는 클래스에서 const가 아닌 생성자를 발견하면 이 진단을 만들어요.

예시

다음 코드는 C@immutable 애너테이션이 있는데도 생성자를 const로 선언하지 않아서 이 진단을 만들어요.

import 'package:meta/meta.dart';

@immutable
class C {
  final int f;

  C(this.f);
}

흔한 해결 방법

클래스가 정말 불변이어야 한다면 생성자에 const 한정자를 붙여요.

import 'package:meta/meta.dart';

@immutable
class C {
  final int f;

  const C(this.f);
}

클래스가 가변(mutable)이라면 @immutable 애너테이션을 제거하면 돼요.

class C {
  final int f;

  C(this.f);
}

더 알아보기