0

How to make Kotlin Annotation parameter's name explicit declaration mandatory?

// Having an annotation class Foo
annotation class Foo(val bar: String)


// This declaration should work
// we explicitly provided parameter name
@Foo(bar = "42")
class X

// This should fail
// we didn't explicitly provide a name
@Foo("42")
class Y 

As far as I understand it's not possible to do with stock Kotlin Compiler and/or IDE? Am I right?

If we're thinking about a custom implementation:

  • Is there an existing solution in Kotlin ecosystem?
  • Is it possible to implement a guard with a Kotlin Compiler Plugin / KSP?
Sergei Rybalkin
  • 3,337
  • 1
  • 14
  • 27

1 Answers1

1

This hack is the only way I can think of without doing something on the compiler end or lint. Create an extra parameter of the same type that has a default value and comes before the parameter you care about. Then if bar = is not specified, it would be ambiguous to pass only a single unnamed parameter, so you are forced to specify it by name.

annotation class Foo(val unused: String = "", val bar: String)

This isn't foolproof, because someone could specify both without naming them.

@Foo("", "x")
Tenfour04
  • 83,111
  • 11
  • 94
  • 154
  • Maybe related: https://stackoverflow.com/questions/37394266/how-can-i-force-calls-to-some-constructors-functions-to-use-named-arguments – Sam Nov 04 '21 at 13:28
  • @Sam, annotation constructors can only accept Strings, primitives, and arrays of Strings or primitives, so Nothing cannot be used. – Tenfour04 Nov 04 '21 at 13:34