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

1
  • To pass an array as a vararg parameter, use spread (*) operator. @OneOf(value = *arrayOf("m", "f"))
    – Miha_x64
    Commented May 19, 2017 at 13:08

4 Answers 4

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

0
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"])
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
1
  • 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) Commented Dec 21, 2020 at 8:20
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)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.