작성
·
336
·
수정됨
0
package enumeration.ex2;
public class DiscountService {
public int discount(ClassGrade grade, int price) {
if (grade == ClassGrade.BASIC) {
return price / 100 * 10;
}
if (grade == ClassGrade.GOLD) {
return price / 100 * 20;
}
if (grade == ClassGrade.DIAMOND) {
return price / 100 * 30;
}
return 0;
}
}
package enumeration.ex2;
public class DiscountServiceTest {
public int discount(ClassGrade grade, int price) {
switch (grade) {
case ClassGrade.BASIC -> {
return price / 100 * 10;
}
case ClassGrade.GOLD -> {
return price / 100 * 20;
}
case ClassGrade.DIAMOND -> {
return price / 100 * 30;
}
default -> {
return 0;
}
}
}
}
안녕하세요. 위의 코드 같이 if 문으로 사용하면 정상적으로 실행이 가능한데
아래 처럼 if 문을 개선된 switch 문으로 바꾸면 왜 컴파일 오류가 뜨는지 정확히 알고 싶습니다.
case 에는 리터럴 상수만 사용 가능하고
참조값은 case에 적을 수 없는 것 같은데 맞나요?
답변 2
1
안녕하세요. 비공식 서포터즈 임형준입니다. 당나귀님처럼 코드변경해보는거 저도 좋아합니다. 아마 Constant expression required
과 같은 컴파일 에러가 발견되었겠죠?
이렇게 뚜렷하게 키워드들이 나오면 저는 공식문서나 스펙으로 한 번 확인해봐요. (멋있잖아요. ㅎㅎ)
https://docs.oracle.com/javase/specs/jls/se23/html/jls-14.html#jls-SwitchLabel
들어가보면 바로 다음 문구를 확인하실 수 있습니다.
> Every case
constant must be either a constant expression (§15.29), or the name of an enum constant (§8.9.1), otherwise a compile-time error occurs.
발번역 해본다면, '모든 case constant 는 constant expression 이거나 enum 상수의 이름이어야 하고 다른 것들은 컴파일 에러가 발생한다.' 라고 합니다.
정리해본다면, case문 안에 상수는
1. constant expression: 보통 final static 으로 선언된 상수를 말합니다.
2. enum 객체 자체(아마 Java 17부터 가능)
이 두가지 경우가 선언될 수 있습니다.
하지만, ClassGrade.BASIC
과 같은 경우는 final static으로 선언된 상수(primitive type 혹은 String)가 아니라 객체이기 때문에 허용이 안됩니다.