KOTLIN · 기초 문법
계약 (Contracts)
Kotlin 계약(Contract)은 컴파일러에게 함수의 동작을 알려줍니다. 스마트 캐스트와 초기화 보장에 활용됩니다.
기초 문법고급contractssmart-castexperimentalcallsInPlace
핵심 설명
Kotlin 계약(Contract)은 컴파일러에게 함수의 동작을 알려줍니다. 스마트 캐스트와 초기화 보장에 활용됩니다.
Kotlin code
import kotlin.contracts.*
@OptIn(ExperimentalContracts::class)
fun requireNotEmpty(value: String?): String {
contract {
returns() implies (value != null)
}
if (value.isNullOrEmpty()) {
throw IllegalArgumentException("값이 비어있습니다")
}
return value
}
@OptIn(ExperimentalContracts::class)
inline fun <R> executeOnce(block: () -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block()
}
fun main() {
val input: String? = "Hello"
val result = requireNotEmpty(input)
// 여기서 result는 non-null로 스마트 캐스트됨
println(result.length)
val value: Int
executeOnce { value = 42 }
println(value) // 초기화 보장됨
}학습 팁
callsInPlace(block, EXACTLY_ONCE) 계약은 val 변수를 람다 내에서 초기화할 수 있게 합니다.
주의할 점
계약은 실험적 API입니다. @OptIn(ExperimentalContracts::class)를 반드시 추가해야 하며, 허위 계약을 작성하면 런타임 오류가 발생합니다.
자주 묻는 질문
계약 (Contracts)란 무엇인가요?
Kotlin 계약(Contract)은 컴파일러에게 함수의 동작을 알려줍니다. 스마트 캐스트와 초기화 보장에 활용됩니다.
계약 (Contracts) 학습 시 주의할 점은 무엇인가요?
계약은 실험적 API입니다. @OptIn(ExperimentalContracts::class) 를 반드시 추가해야 하며, 허위 계약을 작성하면 런타임 오류가 발생합니다.
Continue Learning
Kotlin 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.