2

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 Answer 1

1

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,
)
2
  • 1
    so generic annotations don't exist for kotlin? Commented Sep 18, 2022 at 14:48
  • If you need to specify a class as an argument of an annotation, use a Kotlin class (KClass). Commented Sep 29, 2023 at 7:37

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.