private void validateScoreIsNotNegative(int score) {
if (score < 0) {
throw new IllegalArgumentException(String.format("%s는 0보다 작을 수 없습니다.", score));
}
}
fun validateScoreIsNotNegative(score: Int) {
if (score < 0) {
throw IllegalArgumentException("${score}는 0보다 작을 수 없습니다.")
}
}
자바에서 if는 문(Statement)이지만, 코틀린에서 if는 식(Expression)이다.
private String getPassOrFail(int score) {
if (score >= 50) {
return "P";
} else {
return "F";
}
}
fun getPassOrFail(score: Int): String {
return if (score >= 50) {
"P"
} else {
"F"
}
}
if (0 <= socre && score <= 100) {
if (score in 0..100) {
private String getGradeWithSwitch(int score) {
switch (score / 10) {
case 9:
return "A";
case 8:
return "B";
case 7:
return "C";
default:
return "D";
}
}
fun getGradeWithSwitch(score: Int): String {
return when (score / 10) {
9 -> "A"
8 -> "B"
7 -> "C"
else -> "D"
}
}
fun getGradeWithSwitch2(score: Int): String {
return when (score) {
in 90..99 -> "A"
in 80..89 -> "B"
in 70..79 -> "C"
else -> "D"
}
}
이렇게 in을 활용하여서도 사용 가능하다.