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

Kotlin annotation - Require a parameter is a Constant variable from specific class

我这里有一个函数filter

fun filter(category: String) {
...
}

和一个Class有很多常量字符串

object Constants {
    val CAT_SPORT = "CAT_SPORT"
    val CAT_CAR = "CAT_CAR"
    ...
}

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

我正在寻找类似 @StringRes 的内容。

我知道 Enum 可能会成功,但目前不想进行代码重构。

使用 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) {
    ...
}