omit_obvious_local_variable_types: 지역 변수의 뻔한 타입 표기는 생략하세요
omit_obvious_local_variable_types: 지역 변수의 뻔한 타입 표기는 생략하세요
지역 변수의 타입이 정말 자명한데도 일일이 붙여 쓰면, 코드를 읽는 사람의 주의를 오히려 덜 중요한 곳으로 끌어요. omit_obvious_local_variable_types는 타입이 자명한 초기화된 지역 변수에 타입 표기를 붙이지 말라고 알려주는 린트(lint) 규칙이에요. 말 그대로 omit_local_variable_types에서 "뻔한 타입만 생략"하는 더 유연한 버전이라고 보면 돼요.
본문
상세 설명
초기화된 지역 변수의 타입이 자명할 때는 타입 표기를 붙이지 마세요. 지역 변수는 특히 함수가 작은 현대 코드에서 유효 범위가 아주 짧아요. 타입을 생략하면 독자의 시선이 더 중요한 변수 이름과 초기화 값에 머물게 되니까, 자명한 지역 변수 타입 표기는 생략하는 게 좋아요.
BAD:
List<List<Ingredient>> possibleDesserts(Set<Ingredient> pantry) {
List<List<Ingredient>> desserts = <List<Ingredient>>[];
for (final List<Ingredient> recipe in cookbook) {
if (pantry.containsAll(recipe)) {
desserts.add(recipe);
}
}
return desserts;
}
const cookbook = <List<Ingredient>>[....];
GOOD:
List<List<Ingredient>> possibleDesserts(Set<Ingredient> pantry) {
var desserts = <List<Ingredient>>[];
for (final List<Ingredient> recipe in cookbook) {
if (pantry.containsAll(recipe)) {
desserts.add(recipe);
}
}
return desserts;
}
const cookbook = <List<Ingredient>>[....];
다만 추론된 타입이 변수에 원하던 타입이 아닐 때가 있어요. 예를 들어 나중에 다른 타입의 값을 할당할 생각일 수 있고, 초기화 표현식의 타입이 자명하지 않아서 미래에 코드를 읽을 사람을 위해 이 타입을 문서처럼 남기고 싶을 수도 있어요. 또 특정 타입을 고정해서 가까운 코드, import, 어디든지 있는 의존성의 업데이트가 이 변수의 타입을 조용히 바꿔버린 결과로 컴파일 에러나 런타임 버그가 생기지 않게 하고 싶을 수도 있고요. 그런 경우라면 원하는 타입을 명시해 주면 돼요.
GOOD:
Widget build(BuildContext context) {
Widget result = someGenericFunction(42) ?? Text('You won!');
if (applyPadding) {
result = Padding(padding: EdgeInsets.all(8.0), child: result);
}
return result;
}
호환되지 않는 규칙
omit_obvious_local_variable_types 린트는 다음 규칙과 호환되지 않아요:
always_specify_types
활성화하기
omit_obvious_local_variable_types 규칙을 활성화하려면 analysis_options.yaml 파일의 linter > rules 아래에 omit_obvious_local_variable_types를 추가해요.
linter:
rules:
- omit_obvious_local_variable_types
대신 YAML map 문법으로 린터 규칙을 설정한다면, linter > rules 아래에 omit_obvious_local_variable_types: true를 추가해요.
linter:
rules:
omit_obvious_local_variable_types: true
참고로 이 규칙은 Dart 3.6에서 추가됐고 자동 수정(fix)이 제공돼요.