HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
📝
남득윤 학습 저장소
/
Kotlin docs
Kotlin docs
/
▶️
Conditions and loops
▶️

Conditions and loops

 

If 표현식

코틀린에서, if 는 expression임 즉, 값을 리턴함
그래서 3항 연산자 없음
 
 
if 표현식에 코드 블럭이 적용된 경우 반환 값은 블럭의 마지막 줄임
 
if 표현식의 반환 값을 얻고 싶다면 else 브랜치가 필수임.
notion image
 
'if' must have both main and 'else' branches if used as an expression
 

When 표현식

when 은 전통적인 switch 문과 비슷함
when 은 브랜치의 조건이 충족 될 때까지 argument를 매치함
 
when 은 expression 혹은 statement 로 활용될 수 있음
표현식으로 활용될때는 처음 매칭하는 브랜치의 값이 선택됨
statement로 활용되면 각 브랜치의 개별 값은 무시된다.
if 처럼 브랜치는 blocked 될 수 있고 마지막 표현식의 값이 선택된다.
 
else 브랜치는 다른 모든 브랜치의 조건이 만족되지 않을때 선택된다.
 
when 절이 표현식으로 사용될때 컴파일러가 모든 케이스가 커버 됨을 보장 할 수 없다면 else 브랜치는 필수이다. 예를 들어 enum 혹은 sealed 클래스에서는 보장 할 수 있다.
 
when절 의 조건문 에서는 임의의 표현식, in절, is 를 활용한 타입 채킹 등 다양한 표현식을 지원한다.
 

For loops

for 루프를 통해 iterator 를 제공하는 모든 것을 순회할 수 있습니다.
that is:
  • has a member or an extension function iterator() that returns Iterator<>:
  • has a member or an extension function next()
  • has a member or an extension function hasNext() that returns Boolean.
All of these three functions need to be marked as operator.
 
숫자를 순회하기 위해서 range expression을 사용할 수 있다.
 
range 혹은 array를 사용하는 for loop는 indexed for loop로 컴파일 되기 때문에 iterator 객체를 생성하지 않습니다.
 
배열을 루프하는 다른 방법으로 withIndex 라이브러리 함수를 활용하는 것이 있습니다.
 

While loops, Break and continue in loops

while, do-while 루프 지원
전통적인 break, continue도 지원
var max = a if (a < b) max = b // With else var max: Int if (a > b) { max = a } else { max = b } // As expression val max = if (a > b) a else b
val max = if (a > b) { print("Choose a") a } else { print("Choose b") b }
when (x) { 1 -> print("x == 1") 2 -> print("x == 2") else -> { print("x is neither 1 nor 2") } }
enum class Color { RED, GREEN, BLUE } when (getColor()) { Color.RED -> println("red") Color.GREEN -> println("green") Color.BLUE -> println("blue") // 'else' is not required because all cases are covered } when (getColor()) { Color.RED -> println("red") // no branches for GREEN and BLUE else -> println("not red") // 'else' is required }
fun hasPrefix(x: Any) = when(x) { is String -> x.startsWith("prefix") else -> false }
for (item: Int in ints) { // ... }
for (i in 1..3) { print(i) } //123 for (i in 6 downTo 0 step 2) { print(i) } //6420
fun main() { val array = arrayOf("a", "b", "c") for (i in array.indices) { println(array[i]) } //abc for (a in array) { println(a) } //abc }
for ((index, value) in array.withIndex()) { println("the element at $index is $value") }