Kotlin 注释 - 要求参数是来自特定类的常量变量

Kon*_*Man 2 android annotations kotlin

filter我这里有一个函数

fun filter(category: String) {
...
}
Run Code Online (Sandbox Code Playgroud)

和一个具有许多常量字符串的类

object Constants {
    val CAT_SPORT = "CAT_SPORT"
    val CAT_CAR = "CAT_CAR"
    ...
}
Run Code Online (Sandbox Code Playgroud)

如何确保参数category是常量字符串Constants(或抛出警告)?

我正在寻找类似的东西@StringRes

我知道Enum可能会成功,但此时不喜欢进行代码重构。

gpu*_*nto 6

使用 androidx.annotation 你可以做这样的事情:

object Constants {
    @Retention(AnnotationRetention.SOURCE)
    @StringDef(CAT_SPORT, CAT_CAR)
    annotation class Category

    const val CAT_SPORT = "CAT_SPORT"
    const val CAT_CAR = "CAT_CAR"
}

fun filter(@Constants.Category category: String) {
    ...
}
Run Code Online (Sandbox Code Playgroud)