Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annotations: when is arrayOf needed

Tags:

kotlin

Lets say we have a Java annotation as follows:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Hans {
    String[] value() default {};
}

In Kotlin I am allowed to use the Annotation as follows:

@Hans(value = "test")

As soon as i change the property name from 'value' to 'name' it is not allowed to use this syntax anymore, instead I need to have arrayOf(..).

@Hans(name = arrayOf("test"))

Is that a bug or a design decision and if so what is the reason behind it.

Many thanks in advance Kind regards

like image 621
Raffael Schmid Avatar asked Dec 16 '16 09:12

Raffael Schmid


1 Answers

No, this is not a bug. Java treats the value annotation specially and allows to omit the annotation parameter name when you use it. Kotlin follows this special treatment and also allows you to omit the parameter name, allowing you to write @Hans("test"). Supporting this syntax for array parameters requires to treat the parameter as vararg, so Kotlin does that and allows you to omit the arrayOf.

like image 131
yole Avatar answered Oct 14 '22 11:10

yole