switch_expression_not_assignable 진단: switch 표현식과 case 표현식 타입 불일치

switch_expression_not_assignable 진단: switch 표현식과 case 표현식 타입 불일치

switch 문을 쓸 때 switch에 넘기는 표현식의 타입과 각 case 절에 쓰는 표현식의 타입은 서로 같아야 해요. switch_expression_not_assignable 진단은 이 두 타입이 어긋났을 때 분석기가 알려주는 진단이에요.

출처: switch_expression_not_assignable

본문

설명

분석기는 switch 문의 표현식 타입이 case 절의 표현식 타입에 할당(assign) 가능하지 않을 때 이 진단을 만들어요.

예시

다음 코드는 s의 타입(String)이 0의 타입(int)에 할당 가능하지 않기 때문에 이 진단을 만들어요.

void f(String s) {
  switch (s) {
    case 0:
      break;
  }
}

흔한 해결 방법

만약 case 표현식의 타입이 맞다면, switch 문의 표현식을 올바른 타입이 되도록 바꿔요.

void f(String s) {
  switch (int.parse(s)) {
    case 0:
      break;
  }
}

만약 switch 표현식의 타입이 맞다면, case 표현식을 올바른 타입으로 바꿔요.

void f(String s) {
  switch (s) {
    case '0':
      break;
  }
}

더 알아보기