Kotlin: how to pass array to Java annotation
Asked Answered
T

4

39

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

Tuddor answered 19/5, 2017 at 11:36 Comment(1)
To pass an array as a vararg parameter, use spread (*) operator. @OneOf(value = *arrayOf("m", "f"))Pilar
O
34

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

Ornas answered 19/5, 2017 at 11:43 Comment(0)
L
23

In Kotlin 1.2, it supports array literal in annotation. So the below syntax becomes valid in Kotlin 1.2:

@OneOf(value = ["m", "f"])
Little answered 29/9, 2017 at 18:38 Comment(0)
H
7

As an example from Kotlin docs

// Kotlin 1.2+:
@OneOf(names = ["abc", "foo", "bar"]) 
class C

// Older Kotlin versions:
@OneOf(names = arrayOf("abc", "foo", "bar")) 
class D
Hypochondriasis answered 18/10, 2017 at 12:23 Comment(1)
any idea how to pass this as a variable? like, val someArray = arrayOf("abc", "foo", "bar") I tried it below way and its giving me should be compile time constant exception 1) @OneOf(names = someArray) 2) @OneOf(names = *someArray)Barmaid
S
0

Example of annotation parameters other than value. Non-literals can also be passed inside []

@RequestMapping(value = "/{isbn}", method=[RequestMethod.GET])
fun getBook(@PathVariable isbn: String) : Book = bookRepository.findBookByIsbn(isbn)
Swill answered 20/8, 2019 at 17:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.