Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: how to pass array to Java annotation

I want to use @OneOf annotation from package io.dropwizard.validation;

Java usage:

@OneOf(value = {"m", "f"}) 

Kotlin usage: ???

I've tried this:

 @OneOf(value = arrayOf("m", "f")) 

and this:

 @OneOf(value = ["m", "f"]) 

(EDIT: this example works since Kotlin 1.2, it supports array literal in annotation, thanks @BakaWaii)

All i get is :

Type inference failed. Expected type mismatch:

required: String

found: Array<String>

Kotlin version: 1.1.2-2

like image 255
charlie_pl Avatar asked May 19 '17 11:05

charlie_pl


People also ask

How do you pass an array of strings in Kotlin?

We can use the library function arrayOf() to create an array by passing the values of the elements to the function. Since Array is a class in Kotlin, we can also use the Array constructor to create an array. The constructor takes two parameters: The size of the array, and.

Do Java annotations work in Kotlin?

annotation. Repeatable meta-annotation. This will make it repeatable both in Kotlin and Java. Java repeatable annotations are also supported from the Kotlin side.

Are annotations inherited Kotlin?

Kotlin does not support inherited annotations.

What is use of annotation in Kotlin?

Annotations are used to attach metadata to classes, interface, parameters, and so on at compile time. Annotation can be used by compiler which reflects at runtime. We can change the meaning of the data or program according to annotation values.


1 Answers

The value parameter is automatically converted to a vararg parameter in Kotlin, as described in http://kotlinlang.org/docs/reference/annotations.html#java-annotations.

The correct syntax for this particular case is @OneOf("m", "f")

like image 192
yole Avatar answered Sep 20 '22 14:09

yole