컴퓨터 언어/kotlin

if , when , for , while ?

이건욱 2020. 4. 12. 13:43

if :)

코틀린에서는 if 가 값을 반환합니다. 

따라서 삼항 연산자는 존재 하지 않습니다. ex) condition ? then : else

 

그래서 다음과 같이 전통적인 방법과 표현식을 사용한 방법으로 나눌수 있습니다.

// Traditional usage 
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

 

when :)

when은 흔히 아는 switch 문과 비슷합니다.

일부 분기 조건이 충족될 때까지 모든 분기를 순차적으로 탐색합니다.

when도 마찬가지로 expression 또는 statement로 사용할수 있습니다.

else는 모든 조건을 탐색을 했을 때 충족이 안되면 탑니다.

 

expression을 사용시 else문은 필수입니다.

예시

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

when (x) {
    parseInt(s) -> print("s encodes x")
    else -> print("s does not encode x")
}

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

// 특정한 타입인지 체크 할수도 있습니다.
fun hasPrefix(x: Any) = when(x) {
    is String -> x.startsWith("prefix")
    else -> false
}

// 인수에 아무값도 넣지 않으면 boolean 표현식입니다. 따라서 True이면 실행 입니다.
when {
    x.isOdd() -> print("x is odd")
    x.isEven() -> print("x is even")
    else -> print("x is funny")
}

// kotlin 1.3 부터 다음과 같이 가능합니다.
fun Request.getBody() =
        when (val response = executeRequest()) {
            is Success -> response.body
            is HttpError -> throw HttpException(response.status)
        }

 

 

For Loops :)

for 문은 주어진 값들을 반복하는데에 쓰입니다.

 

간단하게는 아래와 같이 사용이 됩니다.

for (item in collection) print(item)

for (i in 1..3) {
    println(i)
}

//1
//2
//3


for (i in 6 downTo 0 step 2) {
    println(i)
}

//6
//4
//2
//0

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


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

 

While Loops :)

while (x > 0) {
    x--
}

do {
    val y = retrieveData()
} while (y != null) // y is visible here!