2

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.

1
  • perhaps you can program that on your own, it's easy with annotation processor Commented Jul 30, 2019 at 8:43

1 Answer 1

7

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) {
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.