Skip to main content

조건문(statement)이 아닌 조건식(expression)

public static void main(String[] args) {
int max;
// 조건문
if (a > b) {
max = a;
} else {
max = b;
}

// 조건식
int max2 = a > b ? a : b;
}
val max = if (a > b) a else b

in 연산자와 범위 연산자로 조건식 간략하게 만들기

변수 이름 in 시작값..마지막값

val score = 71

// AS_IS
if (score >= 70 && score <= 100) {
}

// TO_BE
if (score in 70..100) {
}

when(switch)

when(x) {
1 -> println("x == 1")
2 -> println("x == 2")
else -> println("x is neither 1 nor 2")
}

// 복수개의 인자를 사용
when(x) {
0, 1 -> println("x == 0 or x == 1")
else -> println("otherwise")
}

// when에 함수의 반환값 사용
val s1 = "123"
val x1 = 123

when (x1) {
s1.toInt() -> println("Ok")
else -> println("Failure")
}

// when에 in 연산자와 범위 지정자 사용
val y = 71
when (y) {
in 1..70 -> println("1 ~ 70")
in 71..100 -> println("71 ~ 100")
!in 1..100 -> println("not 1 ~ 100")
else -> println("else")
}

// when과 is 키워드 함께 사용하기
val str2 = "Hello, world!"
val result = when(str) {
is Stirng -> true
else -> false
}

// 인자가 없는 when
val score = 70
var grade: Char = 'F'
when {
score >= 90 -> grade = 'A'
score in 80 until 90 -> grade = 'B'
score in 70 until 80 -> grade = 'C'
score < 70 -> grade = 'F'
}

// 다양한 자료형의 인자 받기
fun main() {
cases("Hello")
cases(1)
cases(System.currentTimeMillis())
cases(Dto())
}

data class Dto(
val name: String = "Test",
)

fun cases(obj: Any) {
when (obj) {
is String -> println("String")
is Int -> println("Int")
is Long -> println("Long")
else -> println("Unknown")
}
}