제어와 반복 Kotlin


1. for
val items = listOf("apple","banana","kiwifruit")
for (a in items) {
  println(a)
}

for (index in items.indices) {
  println("item at $index is ${items[index]}")
}

2. while
val items = listOf("apple", "banana", "kiwi")
var index=0
while (index < items.size) {
  println("item at $index is ${items[index]}")
  index++
}

3. when, 변수 형식에 구애받지 않는 switch
- case도 필요 없음, break없음

fun describe(obj: Any): String = 
when(obj) {
  1 -> "One"
  "Hello" -> "Greeting"
  is Long -> "Long"
  !is String -> "Not a String"
  else -> "Unknown"
}

return에도 사용가능
fun transform(color: String):Int {
  return when(color) {
    "Red"->0
    "Green"->1
    "Blue"->2
    else -> throw IllegalArgumentException("Invalid color param value")
  }
}

4. ranges
val x = 10
val y = 9
if (x in 1..y+1) {
  println("fits in range")
}

val list = listOf("a","b","c")
if (-1 !in 0..list.lastIndex) {
  println("-1 is out of range")
}
if (list.size !in list.indices) {
  println("list size is out of valid list indices range too")
}

for (x in 1..5) {print(x)}
for (x in 1..10 step 2) {print(x)}
for (x in 9 downTo 0 step 3) {print(x)}
for (x in 1 until 100) {print(x)}

5. collections
for (item in items) {println(item)}

when {"orange" in items -> println("juicy")
  "apple" in items -> println("apple is fine too")
}

fruits
.filter(it.startsWith("a")}
.sortedBy{it}
.map{it.toUpperCase()}
.forEach{println(it)}

6. try/catch
fun test() {
  val result = try{
    count()
  } catch(e:ArithmeticException){
    throw IllegalStateException(e)
  }
}



덧글

댓글 입력 영역