Using Generic Parameter Type in Kotlin Annotations

Viewed 23

I'm trying to define annotation with a type parameter

annotation class BotCommandScopeChat<T>(
    val type: String = "chat",
    val chatId: T,
)

here chatId can be in form of Integer like 1234567890 or String like @supergroup
but intellj says Invalid type of annotation member.

so what I'm doing wrong?

1 Answers

Kotlin annotations can only use the following as construction parameters:

  • Types that correspond to Java primitive types (Int, Long etc.)
  • Strings
  • Classes (Foo::class)
  • Enums
  • Other annotations
  • Arrays of the types listed above

Generic types are not allowed.

In your situation you'll either have to make two constructors, one for each type:

annotation class BotCommandScopeChatIntId(
    val type: String = "chat",
    val chatId: Int,
)

annotation class BotCommandScopeChatStringId(
    val type: String = "chat",
    val chatId: String,
)

Or have two constructor parameters, one for each type:

annotation class BotCommandScopeChat(
    val type: String = "chat",
    val chatIdString: String? = null,
    val chatId: Int? = null,
)

These will have to have default parameters, else users will always have to provide one, even if they don't need to.

Or (and this would be my preference), just use a String, and convert it to an Int if necessary.

annotation class BotCommandScopeChat(
    val type: String = "chat",
    val chatId: String,
)
Related