private void validateScoreIsNotNegative(int score) {
if (score < 0) {
throw new IllegalArgumentException(String.format("%s는 0보다 작을 수 없습니다."), score));
}
}
private String getPassOrFail(int score) {
if (score >= 50) {
return "P";
} else {
return "F";
}
}
fun validateScoreIsNotNegative(score: Int) {
if (score < 0) {
throw IllegalArgumentException("${socre}는 0보다 작을 수 없습니다.}");
}
}
fun getPassOrFail(int score): String{
if (score >= 50) {
return "P"
} else {
return "F"
}
}
Unit(void) 생략Statement이지만Expression이다.프로그램의 문장, 하나의 값으로 도출되지 않는다.
하나의 값으로 도출되는 문장
private String getPassOrFail(int score) {
// java에서 if - else는 Statement라 하나의 값으로 도출되지 않는다.
if (score >= 50) {
return "P";
} else {
return "F";
}
}
private String getPassOrFail(int score) {
// 3항 연산자는 하나의 값으로 취급되는 Expression이다.
return score >= 50 ? "P" : "F";
}
Kotlin에서는 if - else를 Expression으로 사용할 수 있기 때문에 3항 연산자가 없다.
fun getPassOrFail(score: Int): String {
// Kotlin에서 if - else는 Expression이다.
return if (score >= 50) {
"P"
} else {
"F"
}
}
private void validateScoreIsNotNegative(int score) {
if (0 > score && score > 100) {
thorw new IllegalArgumentException("score의 범위는 0이상 100 이하입니다.");
}
}
fun validateScoreIsNotNegative(score: Int) {
if (score !in 0..100) {
thorw IllegalArgumentException("score의 범위는 0이상 100 이하입니다.");
}
}
int num = 10;
num = 20;
switch 대신 when , case 대신 -> , default 대신 else 사용.
fun getGradeWithSwift(score: Int): String {
// Kotlin에서 when은 Expression이다.
return when (score / 10) {
9 -> "A"
8 -> "B"
7 -> "C"
else -> "D"
}
}
fun getGradeWithSwift(score: Int): String {
return when (score) {
in 90..99 -> "A"
in 80..89 -> "B"
in 70..79 -> "C"
else -> "D"
}
}
if / if - else 모두 Java와 문법이 동일하다.
switch 는 when 으로 대체되었다.