1. if문

 

val time = 22
if (time < 10) {
  println("Good morning.")
} else if (time < 20) {
  println("Good day.")
} else {
  println("Good evening.")
}
// Outputs "Good evening."

 

 

 

 

 

2. when문

 

val day = 4

val result = when (day) {
  1 -> "Monday"
  2 -> "Tuesday"
  3 -> "Wednesday"
  4 -> "Thursday"
  5 -> "Friday"
  6 -> "Saturday"
  7 -> "Sunday"
  else -> "Invalid day."
}
println(result)

// Outputs "Thursday" (day 4)

when (2) {
  1, 2 -> println("1 or 2")
  in 3..10 -> println("3~10")
  !in 11..100 -> println("minus"$
}

// 코틀린 공식문서의 재미있는 when 활용 소스코드
fun Request.getBody() =
  when (val response = executeRequest()) {
    is Success -> response.body()
    is HttpError -> throw HttpException(response.status)
}

 

 

 

 

 

3. while 문

 

// while 예제
var i = 0
while (i < 5) {
  println(i)
  i++
}

// do ... while 예제
var i = 0
do {
  println(i)
  i++
  }
while (i < 5)

 

 

 

 

 

4. for문

 

val nums = arrayOf(1, 5, 10, 15, 20)
for (x in nums) {
  println(x)
}
// 1 5 10 15 20

for ((index, value) in nums.withIndex()) {
  println("$index: $value")
}
// 0: 1
// 1: 5
// 2: 10
// 3: 15
// 4: 20

 

fun main() {
  for (nums in 5..15) {
    if (nums == 10) {
      continue
    }
    if (nums == 12) {
      break
    }
    println(nums)
  }
}

/*

5
6
7
8
9
11

*/

 

 

 

 

 

5. array, list, map을 활용한 반복문 예제 소스코드

 

 - array

val array = arrayOf(1, 2, 3)
for (item in array) {
    println(item) // Prints 1, 2 and 3 on separate lines.
}

var index = 0
while (index < array.size) {
    println(array[index]) // Prints 1, 2 and 3 on separate lines.
    index++
}

 

 - list, mutabl list

val list1 = listOf("a", "b", "c")
val list2 = listOf("d", "e", "f")
var combinedList: MutableList<String> = (list1 + list2).toMutableList() // Combine multiple lists and convert to MutableList for modification and deletion.
println(combinedList) // [a,b,c,d,e,f]

combinedList[0] ="z"// Modify data at index 
println(combinedList) //[z,b,c,d,e,f]

combinedList.removeAt(0) // Remove data at index 
println(combinedList)//[b,c,d,e,f]

 

 - set

 Set는 순서가 없으므로 인덱스로 접근하는 것이 불가능합니다. 따라서 for 문만 사용할 수 있습니다.

val set1 = setOf(10 ,20)
val set2= setOf(30)
val set3= setOf(40)

var resultSet=set1+set2+set3

resultSet+=50

resultSet-=40

println(resultSet) //[10 ,20 ,30 ,50]

 

 - map

 Map은 키-값 쌍으로 데이터를 저장합니다. for 문을 이용하여 각 키-값 쌍에 접근할 수 있습니다. Map 역시 Set처럼 인덱스로 직접 접근하는 것이 불가능하므로 while 문으로 반복하는 것은 불가능합니다.

val map = mapOf("one" to 1,"two" to 2,"three" to 3)

for ((key,value )in map){
   println("$key -> $value") 
}

// Note: Maps also do not support access by an index like lists or arrays.

 

 

 

+ Recent posts