뭐라도 끄적이는 BLOG

Kotlin 제어문(조건문: if/when, 제어문: for/while) 본문

Kotlin

Kotlin 제어문(조건문: if/when, 제어문: for/while)

Drawhale 2023. 7. 1. 05:53

Conditional expressions

Kotlin은 조건식을 위해 if와 when을 제공한다. if와 when중 when을 사용하는 것을 더 추천한다.

If you have to choose between if and when, we recommend using when as it leads to more robust and safer programs. - Kotlin공식 문서

if

if를 사용하려면 괄호안에 조건식을 추가하고 중괄호 안에 결과가 참인 경우 수행할 작업을 추가한다.

val d: Int
val check = true

if (check) {
    d = 1
} else {
    d = 2
}

println(d)
// 1

Kotlin에는 삼항 연사자(condition ? then : else)가 없다. 대신 if를 표현식으로 사용할 수 있다. if를 표현식으로 사용할 때 중괄호를 사용하지 않는다.

val a = 1
val b = 2

println(if (a > b) a else b) // Returns a value: 2

when

여러 분기가 있는 조건식일때 when을 사용한다. when은 statement로 사용하거나 expression으로 사용할 수 있다.

조건식은 괄호 안에 수행할 작업은 중괄호 안에 작성한다. 각 분기에서 `->`를 사용하여 각 조건과 각 작업을 구분한다.

val obj = "Hello"

when (obj) {
    // Checks whether obj equals to "1"
    "1" -> println("One")
    // Checks whether obj equals to "Hello"
    "Hello" -> println("Greeting")
    // Default statement
    else -> println("Unknown")     
}
// Greeting

모든 분기 조건 중 하나가 만족될 때까지 모든 분기 조건이 순차적으로 확인된다. 그중 가장 먼저 조건이 참이된 분기만 실행된다.

When의 조건의 형식으로 Any를 사용하면 어떤 자료형도 받을 수 있다. Any는 자료형중 최상위 자료형이다.

when(a:Any){
    1-> println("정수 1")
    "string"-> println("string")
    is Long-> println("long")
    is String-> println("type string")
    else -> println("어떤것도 만족하지 않습니다.")
}

when을 표현식으로 사용하는 예이다. when 구문은 변수에 즉시 할당된다.

val obj = "Hello"    

val result = when (obj) {
    // If obj equals "1", sets result to "one"
    "1" -> "One"
    // If obj equals "Hello", sets result to "Greeting"
    "Hello" -> "Greeting"
    // Sets result to "Unknown" if no previous condition is satisfied
    else -> "Unknown"
}
println(result)
// Greeting

when이 표현식으로 사용되는 경우 else는 필수로 작성해야한다.

val temp = 18

val description = when {
    // If temp < 0 is true, sets description to "very cold"
    temp < 0 -> "very cold"
    // If temp < 10 is true, sets description to "a bit cold"
    temp < 10 -> "a bit cold"
    // If temp < 20 is true, sets description to "warm"
    temp < 20 -> "warm"
    // Sets description to "hot" if no previous condition is satisfied
    else -> "hot"             
}
println(description)

when에서 괄호에 조건식을 넣는 경우 분기에서 등호나 부등호의 사용을 할 수 없다. 괄호가 없다면 각 분기에서 조건을 판단해야 하기 때문에 등호나 부등호의 사용이 가능하다.

다양한 when 사용법

when (x) {
    0, 1 -> print("x == 0 or x == 1")
    else -> print("otherwise")
}

여러 케이스에 대한 같은 작업을 정의하기 위해 한 줄에 쉼표로 조건을 결합할 수 있다.

when (x) {
    in 1..10 -> print("x is in the range")
    in validNumbers -> print("x is valid")
    !in 10..20 -> print("x is outside the range")
    else -> print("none of the above")
}

in, !in을 이용하여 특정 값 범위를 체크할 수 있다.

fun hasPrefix(x: Any) = when(x) {
    is String -> x.startsWith("prefix")
    else -> false
}

is !is를 이용하여 값이 특정 유형의 값인지 확인할 수 있다.

 

Ranges

loop를 보기전 loop가 반복할 range를 구성하는 방법을 먼저 살펴본다.

  • range를 만드는 가장 일반적인 방법은 (..)연산자를 사용하는 것이다. 예) `1..4`는 1,2,3,4를 나타낸다.
  • 마지막 값을 포함하지 않는 range를 선언하기 위해선 until을 사용한다. 예) `1 until 4`는 1,2,3을 나타낸다.
  • range를 역순으로 선언하려면 downTo를 사용한다. 예) `4 downTo 1`은 4,3,2,1을 나타낸다.
  • 1이 아닌 단계로 증가하는 range를 선언하기 위해 step과 원하는 증가 연산을 사용한다. 예) `1..5 step 2`는 1,3,5를 나타낸다.

Char에서도 동일한 작업을 수행할 수 있다.

  • `'a'..'d'` 는 'a','b','c','d'를 나타낸다.
  • `'z' downTo 's' step 2`는 'z','x','v','t'를 나타낸다.

Loops

값의 범위를 반복하며 작업을 수행하기 위해 for을 사용하고 특정 조건이 충족될 때까지 작업을 계속하려면 while을 사용한다.

for

for은 iterator를 제공하는 모든 것을 반복할 수 있다. Java의 foreach와 같다고 생각하면 된다.

for (number in 1..5) { 
    print(number)
}
// 12345
val cakes = listOf("carrot", "cheese", "chocolate")

for (cake in cakes) {
    println("Yummy, it's a $cake cake!")
}
// Yummy, it's a carrot cake!
// Yummy, it's a cheese cake!
// Yummy, it's a chocolate cake!

인덱스가 있는 배열이나 리스트를 반복하려면 아래와 같이 사용할 수 있다.

for (i in array.indices) {
    println(array[i])
}

withIndex 함수를 사용할 수도 있다.

for ((index, value) in array.withIndex()) {
    println("the element at $index is $value")
}

while

while은 조건이 참인동안 코드블록을 실행하는 while과 코드 블록을 먼저 실행한 다음 조건식을 확인하는 do-while이 있다.

var cakesEaten = 0
while (cakesEaten < 3) {
    println("Eat a cake")
    cakesEaten++
}
// Eat a cake
// Eat a cake
// Eat a cake
var cakesEaten = 0
var cakesBaked = 0
while (cakesEaten < 3) {
    println("Eat a cake")
    cakesEaten++
}
do {
    println("Bake a cake")
    cakesBaked++
} while (cakesBaked < cakesEaten)
// Eat a cake
// Eat a cake
// Eat a cake
// Bake a cake
// Bake a cake
// Bake a cake

Control flow | Kotlin Documentation (kotlinlang.org)

 

Control flow | Kotlin

 

kotlinlang.org

 

반응형

'Kotlin' 카테고리의 다른 글

Kotlin Lambda  (0) 2023.07.03
Kotlin 함수  (0) 2023.07.03
Kotlin 변수와 데이터 타입  (0) 2023.07.01
Hello Kotlin  (0) 2023.06.30