Kotlin mandatory explicit annotation parameter names? @Foo(>>bar<< = 42)

519 Views Asked by At

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

There are 1 best solutions below

2
Tenfour04 On

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")