switch_on_type 진단: Type 값에 switch를 쓰지 말아야 할 때

switch_on_type 진단: Type 값에 switch를 쓰지 말아야 할 때

타입을 분기해서 처리하고 싶을 때 runtimeType 같은 Type 값에 switch를 쓰고 싶어질 수 있어요. 그런데 그렇게 하면 오히려 안정성이 떨어져요. switch_on_typeType 값이나 Type에 대한 toString 호출을 switch 대상으로 쓰는 걸 막아 주는 린트 진단이에요.

출처: switch_on_type

본문

설명

분석기는 switch 문이나 switch 표현식이 Type의 값, 또는 Type에 대한 toString 호출을 대상으로 사용될 때 이 진단을 만들어요.

예시

다음 코드는 switch 문이 Type 값에 사용되기 때문에 이 진단을 만들어요.

void f(Object o) {
  switch (o.runtimeType) {
    case const (int):
      print('int');
    case const (String):
      print('String');
  }
}

흔한 해결 방법

변수 자체에 패턴 매칭(pattern matching)을 사용해요.

void f(Object o) {
  switch (o) {
    case int():
      print('int');
    case String():
      print('String');
  }
}

더 알아보기