Hanbit the Developer

Kotlin Documentation | Opt-in requirements 본문

Mobile/Kotlin

Kotlin Documentation | Opt-in requirements

hanbikan 2023. 5. 24. 16:24

Kotlin Documentation 시리즈에 대해

Category: Standard library

문서 링크: https://kotlinlang.org/docs/opt-in-requirements.html


API가 실험적이거나 바뀔 예정이라면 opt-in을 붙여 API 사용자에게 이를 알릴 수 있다.

Opt in to using API

Propagating opt-in

opt-in requirement annotation을 통해 opt-in을 지정할 수 있다. 이때 opt-in이 전파되기 때문에 관련 함수 등에 모두 어노테이션을 달아야 한다.

// Library code
@RequiresOptIn(message = "This API is experimental. It may be changed in the future without notice.")
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
annotation class MyDateTime // Opt-in requirement annotation

@MyDateTime
class DateProvider // A class requiring opt-in
// Client code
fun getYear(): Int {
    val dateProvider: DateProvider // Error: DateProvider requires opt-in
    // ...
}

@MyDateTime
fun getDate(): Date {
    val dateProvider: DateProvider // OK: the function requires opt-in as well
    // ...
}

fun displayDate() {
    **println(getDate()) // Error: getDate() requires opt-in**
}

Non-propagating opt-in

전파를 원하지 않는 경우 @OptIn 어노테이션을 마킹한다:

// Client code
@OptIn(MyDateTime::class)
fun getDate(): Date { // Uses DateProvider; doesn't propagate the opt-in requirement
    val dateProvider: DateProvider
    // ...
}

fun displayDate() {
    **println(getDate()) // OK: opt-in is not required**
}

파일 내 모든 함수와 클래스가 opt-in을 요구하는 경우 file-level annotation을 파일 최상단에 추가한다.

// Client code
@file:OptIn(MyDateTime::class)

Module-wide opt-in

opt-in을 사용하는 곳마다 어노테이션을 달기를 원치 않는 경우, 모듈 전체에 opt-in을 할 수 있다. 컴파일 시 opt-in=org.mylibrary.OptInAnnotation과 같은 옵션을 달아줌으로써, 해당 모듈 내 모든 declaration에 @OptIn(OptInAnnotation::class)를 다는 효과가 발생한다.

Require opt-in for API

Create opt-in requirement annotations

**@RequiresOptIn**
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
annotation class MyDateTime

다음과 같은 요구 조건이 있다:

  • BINARY or RUNTIME retention(*코틀린의 AnnotationRetention.BINARY는 자바의 RetentionPolicy.CLASS에 해당합니다.)
  • No EXPRESSION, FILE, TYPE, or TYPE_PARAMETER among targets
  • No parameters.

@RequiresOptIn에서 다음과 같은 level을 가질 수 있다:

  • RequiresOptIn.Level.ERROR. Opt-in을 달지 않으면 컴파일이 안 된다. Default level
  • RequiresOptIn.Level.WARNING. Opt-in이 필수가 아니며 컴파일러가 warning을 띄운다.

이는 다음과 같이 명시할 수 있다:

@RequiresOptIn(level = RequiresOptIn.Level.WARNING, message = "This API is experimental. It can be incompatibly changed in the future.")

Opt-in requirements for pre-stable APIs

해당 어노테이션이 달렸던 API가 stable하게 되었을 경우, 해당 어노테이션을 제거해야 한다. 하지만 경우에 따라서 deprecated된 함수를 그대로 사용해야 할 때도 있다. 이 경우 @Deprecated 어노테이션을 추가한다:

@Deprecated("This opt-in requirement is not used anymore. Remove its usages from your code.")
@RequiresOptIn
annotation class ExperimentalDateTime