[Kotlin] 조건문

백마금편·2022년 8월 3일
0

Kotlin

목록 보기
4/5
post-thumbnail

조건문

IF문

Java

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";
    }
}

Kotlin

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) 생략
  • Java에서 if - elses는 Statement이지만
    Kotlin에서는 Expression이다.

Expression과 Statement

Statement

프로그램의 문장, 하나의 값으로 도출되지 않는다.

Expression

하나의 값으로 도출되는 문장

Java

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

Kotlin에서는 if - else를 Expression으로 사용할 수 있기 때문에 3항 연산자가 없다.

fun getPassOrFail(score: Int): String {	
	// Kotlin에서 if - else는 Expression이다.
	return if (score >= 50) {	
    	"P"
    } else {
    	"F"
    }
}

범위 조건문

Java

private void validateScoreIsNotNegative(int score) {
	if (0 > score && score > 100) {
    	thorw new IllegalArgumentException("score의 범위는 0이상 100 이하입니다.");
    }
}

Kotlin

fun validateScoreIsNotNegative(score: Int) {	
	if (score !in 0..100) {
    	thorw IllegalArgumentException("score의 범위는 0이상 100 이하입니다.");
    }
}

switch와 when

switch

Java

int num = 10;
num = 20;

Kotlin

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와 문법이 동일하다.

  • Kotlin에서는 Expression으로 취급

switchwhen 으로 대체되었다.

profile
뭐 어떻게 잘 되겠지

0개의 댓글