[Kotlin] Kotlin 기본 문법 - 3

Kotlin 기본 문법 배우기 - 3

참고 사이트

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

Collections

1
2
3
for (item in items) {
    println(item)
}
1
2
3
4
5
6
val items = setOf("apple", "banana", "kiwifruit")
when {
    "orange" in items -> println("juicy")
    "apple" in items -> println("apple is fine too")
}
// -> apple is fine too
1
2
3
4
5
6
7
val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
fruits
    .filter { it.startsWith("a") }
    .sortedBy { it }
    .map { it.toUpperCase() }
    .forEach { println(it) }
// -> APPLE AVOCADO

Nullable values and null checks

Return null if str does not hold an integer

1
2
3
fun parseInt(str: String): Int? {
    // ...
}
1
2
3
4
5
6
7
8
9
10
11
12
13
fun printProduct(arg1: String, arg2: String) {
    
    val x = parseInt(arg1)
    val y = parseInt(arg2)

    // Using `x * y` yields error because they may hold nulls.
    if (x != null && y != null) {
        // x and y are automatically cast to non-nullable after null check
        println(x * y)
    } else {
        println("'$arg1' or '$arg2' is not a number")
    }
}

Type checks and automatic casts

1
2
3
4
5
6
7
8
9
fun getStringLength(obj: Any): Int? {
    if (obj is String) {
        // `obj` is automatically cast to `String` in this branch
        return obj.length
    }

    // `obj` is still of type `Any` outside of the type-checked branch
    return null;
}