Search code examples
androidkotlinannotations

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


I have a function filter here

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

and a Class with many constant string

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

How to ensure the parameter category is a constant string from Constants (or throw warning)?

I am looking for something like @StringRes.

I know Enum may do the trick but prefer not to code refactor at this moment.


Solution

  • Using androidx.annotation you can do something like this:

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