[Kotlin] Kotlin 기본 문법 - 2

Kotlin 기본 문법 배우기 - 2

참고 사이트

  • 본 포스팅은 많은 부분들이 생략되어있습니다.

Conditional expressions

1
2
3
4
5
6
7
fun maxOf(a: Int, b: Int): Int {
    if (a > b) {
        return a
    } else {
        return b
    }
}

or

1
fun maxOf(a: Int, b: Int) = if (a > b) a else b

for loop

1
2
3
4
val items = listOf("apple", "banana", "kiwifruit")
for (item in items) {
    println(item)
}

or

1
2
3
4
val items = listOf("apple", "banana", "kiwifruit")
for (index in items.indices) {
    println("item at $index is ${item[index]})
}

while loop

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

when expression

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
fun describe(obj: Any): String =
    when (obj) {
        1          -> "One"
        "Hello"    -> "Greeting"
        is Long    -> "Long
        !is String -> "Not a string"
        else       -> "Unknown"
    }

fun main() {
    println(describe(1)) // One
    println(describe("Hello")) // Greeting
    println(describe(1000L)) // Long
    println(describe(2)) // Not a String
    println(describe("other")) // Unknown
}

Ranges

1
2
3
4
5
val x = 10
val y = 9
if (x in 1..y+1) {
    println("fits in range")
}
1
2
3
4
5
6
7
8
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")
}
1
2
3
for (x in 1..5){
    print(x) // 12345
}
1
2
3
4
5
6
for (x in 1..10 step 2) {
    print(x) // 13579
}
for (x in 9 downTo 0 step 3) {
    print(x) // 9630
}