Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to express array annotation argument in Kotlin?

When annotation has an array argument with basic type like String or Int it is straightforward how to use that:

public @interface MyAnnotation{
  String[] props();
}

@MyAnnotation(props = ["A", "B", "C"])
class Foo {}

Unfortunately that does not work for values that are annotations themselves.

An example is org.springframework.context.annotation.PropertySources:

public @interface PropertySources {
  PropertySource[] value();
}

public @interface PropertySource { 
  String[] value();
}

In Java syntax usage is

@PropertySources({
    @PropertySource({"A", "B", "C"}),
    @PropertySource({"D", "E", "F"}),
})
class Foo{}

But in Kotlin the code with similar approach does not compile

@PropertySources([
    @PropertySource(["A", "B", "C"]),
    @PropertySource(["D", "E", "F"]),
])
class Foo{}

How to express this annotation array nesting construction in Kotlin?

like image 329
diziaq Avatar asked Nov 17 '25 19:11

diziaq


1 Answers

Add value = and remove the @ from the child annotation declaration:

@PropertySources(value = [
  PropertySource("a", "b"),
  PropertySource("d", "e"),
])
class Foo

Also note that @PropertySource is @Repeatable so you can do:

@PropertySource("a", "b")
@PropertySource("d", "e")
class Foo
like image 176
Tom Avatar answered Nov 19 '25 10:11

Tom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!