조건문

if문

var max = a
if(a< b) max = b

// with else
if(a> b){
	max=a
}else{
	max=b
}

//as expression
max=if(a > b) a else b

// you can alse use `else if` in expressions:
val maxLimit - 1
val maxOrLimit = if(maxLimit > a) maxLimit else if (a>b) a else b

 

 

when문

여러 케이스에 대해 구분하기 위해 사용 / if문을 사용하기엔 비교적 케이스가 많은 경우 사용

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

 

enum클래스에서도 사용할수 있음

enum class Bit{
	ZERO, ONE
}


Val numericValue = when (getRandomBit()){
	Bit.ZERO -> 0
	Bit.ONE -> 1 
}

 

조건에 범위를 설정해야할 경우  in 연산자를 사용

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

 

 

반복문

for 문

for (item in collection) print (item)

for (item : int in ints){
	// ```
}

 

//기본적인 for문
for(i in 1..5 /* 1<= .. <=5*/) println(i)
// 12345
    
for(i in 5 downTo 1 /* 5>= .. >=1 큰수에서 작은수로*/)println(i)
// 54321

for(i in 1..5 step 2 /* 1<= .. <=5 step 몇번 건너뛸껀지*/)println(i)
// 135

 

while문

while(x>0){
	x--
}

do{
	val y - retrieveData()
}while(y!=null)

'Kotlin' 카테고리의 다른 글

[Kotlin] 클래스  (0) 2024.10.23
[Kotlin] 함수  (0) 2024.10.23
[Kotiln] 연산자  (0) 2024.10.22
[Kotlin] 변수의 선언  (0) 2024.10.21
[Kotlin] Kotlin 코틀린  (0) 2024.10.21