# 확장 함수 (Extension Functions)
- 기존 클래스에 새로운 함수를 추가할 수 있는 기능이다.
fun 키워드와 함께 정의하며, 확장하려는 클래스의 이름을 접두사로 사용한다.
- 확장 함수의 정의와 사용
fun String.removeWhitespace(): String {
return this.replace(" ", "")
}
fun main() {
val text = "Hello Kotlin"
println(text.removeWhitespace())
}
# 확장 함수의 특징
- 기존 클래스의 소스 코드를 변경하지 않고도 새로운 기능을 추가할 수 있다.
- 실제로는 해당 클래스의 인스턴스에 대해 정적으로 호출된다.
- 같은 이름의 함수가 클래스에 이미 정의되어 있다면, 그 함수가 우선 호출된다.
- 확장 함수와 Nullable 타입
fun String?.isNullOrEmpty(): Boolean {
return this == null || this.isEmpty()
}
fun main() {
val nullString: String? = null
val nonNullString: String? = "Kotlin"
println(nullString.isNullOrEmpty())
println(nonNullString.isNullOrEmpty())
}
# 코루틴 (Coroutines)
- Kotlin의 비동기 프로그램을 위한 경량 스레드이다.
- 스레드보다 가벼운 단위로, 효율적으로 비동기 작업을 처리할 수 있다.
- 코루틴의 기본 사용법
launch와 async 같은 빌더 함수를 사용하여 시작할 수 있다.
launch : 결과를 반환하지 않는다.
async : 결과를 반환하는 코루틴을 만든다.
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
delay(1000L)
println("World!")
}
println("Hello,")
}
- 코루틴 빌더
import kotlinx.coroutines.*
fun main() = runBlocking {
val deferred: Deferred<Int> = async {
delay(1000L)
42
}
println("The answer is ${deferred.await()}")
}
- 코루틴 스코프
- 코루틴은
CoroutineScope 내에서 실행된다.
runBlocking, GlobalScope, 그리고 사용자 정의 스코프를 사용하여 코루틴을 관리할 수 있다.
import kotlinx.coroutines.*
fun main() = runBlocking {
coroutineScope {
launch {
delay(1000L)
println("Coroutine scope")
}
}
println("runBlocking")
}
- 코루틴 컨텍스트
- 코루틴의 동작을 정의하는 요소들의 모음이다. 여기에는 디스패처, 예외 처리기 등이 포함된다.
import kotlinx.coroutines.*
fun main() = runBlocking {
launch(Dispatchers.Default) {
println("Running in the Default dispatcher")
}
}