앱 개발/Kotlin

Expression VS Statement

태기 2023. 2. 21. 20:55

<< git 소스코드 >>

 

간단하게 ,

무언가를 투닥투닥 해서 값을 만들어내면 Expression
결과가 값이 아닌 다른 형태로 나오면 Statement

라고 이해하면 된다.

 

예시로 이전 포스팅의 checkNum 메서드를 가져와보면

fun checkNum(score: Int){
    when(score){
        0 -> println("this is 0")
        1 -> println("this is 1")
        2,3 -> println("this is 2 or 3")
        else -> println("I don't know")
    }

    var b = when(score) {
        1 -> 1
        2 -> 2
        else -> 3
    }

    when (score){
        in 90..100 -> println("You are genius")
        in 80..90 -> println("not bad")
        else -> println("okay")
    }
}

첫 번째 when과 마지막 when은 결과가 값이 아닌 println 메서드를 호출하므로 Statement이고, 두 번째 when은 값을 넣어주기 때문에 Expression이다.

 

Tip.

- 코틀린에서 모든 function은 Expression이다. 반환값이 아무것도 안 적혀있어도 Unit을 반환하기 때문