Control flow 라고도 불리는 조건문은 현실에서 특정 조건이 맞을 때만 행동하는것과 비슷하게 작동한다.
if
, if-else
, nested if-else
, if-else if ladder
종류가 있다.
val condition: Boolean = true
if(condition) {
"condition is True!"
}
condition
에는 true
또는 false
만 들어갈 수 있다.condition
이 true
일 때만 코드가 실행된다.if
식은 항상 결과를 돌려준다.if
는 값을 반환match
파트에서 match
는 값을 반환하는 "식 (expression)" 이라고 설명했다.if
식은 값을 리턴한다.match
식과 비슷하게 if
도 "식 (expression)"으로 사용할 수 있다.// if가 수식(expression) 으로 사용
val a: Int = 1
val b: Int = 2
val smallerNum = if(a < b) a else b // if 는 a의 값을 반환
println(smallerNum) // 1
// if가 문장(statement) 로 사용
val c: Int = 3
val d: Int = 4
if (c < d) println("d is larger!")
if
의 조건이 거짓이면 else 에 속하는 코드가 실행된다.
val a: Int = 1
val b: Int = 2
if (a == b) {
println("a and b is equal!") // 실행 X
} else {
println("a and b is NOT equal!") // 실행 O
}
if
와 else
는 중첩해서 사용할 수 있다.
if (condition1) {
if (condition2) {
// condition_1 = true & condition_2 = true
}
else {
// condition_1 = true & condition_2 = false
}
} else {
if (condition2) {
// condition_1 = false & condition_2 = true
} else {
// condition_1 = false & condition_2 = false
}
}
else if
를 사용해 조금 더 복잡한 구성을 만들 수 있다.
val condition1: Boolean = true
val condition2: Boolean = false
if(condition1) {
// 컨디션1이 참
"condition 1 is True!"
} else if (condition2) {
// 컨디션1은 거짓 컨디션2는 참
// 컨디션2가 참이어도 컨디션1이 참이면 실행되지 않는다.
"condition 1 is false and condition 2 is true!"
} else {
// 컨디션1 과 컨디션2 모두 거짓
"Both condition 1 and condition 2 are false!"
}