Mobile/Kotlin

[Kotlin] 4장 고급 기능

Tinkies 2025. 3. 8. 02:25

1. 고차 함수와 람다 표현식

fun operateOnNumbers(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
    return operation(a,b)
}

fun main() {
    val sum = operateOnNumbers(5,3, { x, y -> x + y }) 
    println("Sum: $sum"); // result: 8
}

 

간단한 함수 정의를 위해 사용되는 익명 함수로, 위 예제에 { x, y -> x + y } 가 람다 표현식입니다.


2. 컬렉션 처리 (List, Map, Set)

  • List: 순서가 있는 컬렉션.
fun main() {
    val list = listOf(1,2,3,4);

    list.forEach { println(it) }
}
  • Map: 키-값 쌍으로 이루어진 컬렉션
fun main() {
    val map = mapOf("one" to 1, "two" to 2)
    map.forEach { (key, value) -> println("$key: $value") }
}
  • Set: 중복을 허용하지 않는 순서 없는 컬렉션 
fun main() {
    val set = setOf(1,2,2,3)
    println(set) // 출력: [1,2,3]
}

3. Null 안전성

코틀린은 NullPointerException을 방지하기 위해 Null 안전성을 지원합니다. 변수에 ?를 사용하여 null을 허용할 수 있습니다. 

var name: String? = null
println(name?.length) // null 안전 호출

 

또는 !! 연산자를 사용하여 null이 아님을 보장할 수 있습니다.

println(name!!.length); // name이 null일 경우 예외 발생

4. 확장 함수

기존 클래스에 새로운 함수를 추가할 수 있는 기능으로, 기존 클래스를 수정하지 않고도 기능을 확장할 수 있습니다.

fun main() {
    fun String.addExclamation() = this + "!"
    var greeting = "Hello".addExclamation() // result: Hello!
    println(greeting)
}

 

 

GitHub - Koras02/kotlin-blogin: https://thinky.tistory.com/category/Mobile/Kotlin

https://thinky.tistory.com/category/Mobile/Kotlin. Contribute to Koras02/kotlin-blogin development by creating an account on GitHub.

github.com

 

LIST