3

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?

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

2 Comments

The trick is in the "value =". Ok, great. Are you sure the second code block compiles?
Yes, note i used latest kotlin (1.6.10)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.