Search
castle

표준 라이브러리

패키지 주요 내용 대표 함수 / 클래스
kotlin 기본 자료형, 타입 변환, null 안전성, 문자열, 수학 함수 등 핵심 기능 let, apply, also, run, takeIf, check, require, lazy, Pair, Triple
kotlin.collections 컬렉션(리스트, 셋, 맵) 관련 기능 listOf, mutableListOf, setOf, mapOf, filter, map, forEach, groupBy, sortedBy, associate
kotlin.ranges 범위(Range)와 진행(Step) .. 연산자, until, downTo, step, IntRange, CharRange
kotlin.sequences 지연(Lazy) 처리 시퀀스 sequenceOf, .asSequence(), map, filter, take, generateSequence
kotlin.text 문자열 처리 확장 함수 substring, split, replace, trim, uppercase, lowercase, Regex, toRegex
kotlin.io 입출력(IO) 기본 기능 readLine, println, File.readText, File.writeText, File.useLines
kotlin.concurrent 동시성 관련 지원 (주로 JVM) thread, Timer, schedule
kotlin.reflect 런타임 리플렉션(Reflection) KClass, ::class, memberProperties, functions
kotlin.time 시간 및 Duration API Duration, measureTime, measureTimedValue, toDuration
kotlin.math 수학 관련 함수 sqrt, pow, abs, roundToInt, sin, cos, PI, E
  • collections : filter, map, forEach
    • it, this : method(filter 등)가 처리할 data 요소, return type == object type
fun main() {
    val names = listOf("aa", "abb", "bcc", "ccc")

    val aList = names.filter { it.startsWith("a") }
    aList.forEach { println(it) }
}
  • 스코프 함수
함수 객체 접근 방식 반환 값 주 사용 목적 사용 예
let it 람다 결과 null 안전 호출, 결과 변환 val len = str?.let { it.length }
apply this 객체 자체 객체 초기화 val p = Person().apply { name="Tom"; age=20 }
also it 객체 자체 부가 작업 (로깅, 디버깅) list.also { println("size=${it.size}") }
run this 람다 결과 객체 컨텍스트에서 계산/변환 val text = person.run { "$name, $age" }
with this 람다 결과 특정 객체 여러 속성 다룰 때 with(file) { readText() }
  • let : Null 안전 함수
    • transaction code block 실행
    • null 발견 시 block 단위로 실행 취소
fun processNonNullString(str: String) {}

fun main() {
    val str: String? = null
    //processNonNullString(str)       
    // compilation error: str can be null
    val length = str?.let { 
		    println("null?")
        println("let() called on $it")        
        // str == null -> 무시
        // str != null -> let() called on Hello
        processNonNullString(it)      // OK: 'it' is not null inside '?.let { }'
        it.length
    }
}

fun main() {
    val numbers = mutableListOf("one", "two", "three", "four", "five")
    val resultList = numbers.map { it.length }.filter { it > 3 }
    println(resultList) 
}

fun main() {
    val numbers = mutableListOf("one", "two", "three", "four", "five")
    numbers.map { it.length }.filter { it > 3 }.let { 
        println(it) // [5, 4, 4]
        // and more function calls if needed
    } 
}
  • also : Unit lambda 함수 실행
    • inline fun <T> T.also(block: (T) -> Unit): T
fun main() {
    val numberList = mutableListOf<Double>()
    numberList.also { println("Populating the list : $numberList") }    
    // Populating the list : []
        .apply {
            add(2.71)
            add(3.14)
            add(1.0)
        }
        .also { println("Sorting the list : $it") } 
        // Sorting the list : [2.71, 3.14, 1.0]
        .sort()
        .also { println("Sorted the list : $it") }  
        // Sorted the list : [1.0, 2.71, 3.14]
}
  • check :
    • inline fun check(value: Boolean)
  • require(condition, false_message) : condition이 거짓 → false_message 출력
    • false_message : lambda 형식
import kotlin.test.*

fun main() { 

    fun getIndices(count: Int): List<Int> {
        require(count >= 0) { "Count must be non-negative, was $count" }
        // ...
        return List(count) { it + 1 }
    }

    // getIndices(-1) // will fail with IllegalArgumentException
    // Exception in thread "main" java.lang.IllegalArgumentException: Count must be non-negative, was -1
    // at FileKt.main$getIndices (File.kt:6) 
    // at FileKt.main (File.kt:11) 
    // at FileKt.main (File.kt:-1) 

    println(getIndices(3)) // [1, 2, 3] 

}
left
right

C

Contents