37

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

charlie_pl
  • 2,898
  • 4
  • 25
  • 39
  • To pass an array as a vararg parameter, use spread (*) operator. `@OneOf(value = *arrayOf("m", "f"))` – Miha_x64 May 19 '17 at 13:08

4 Answers4

33

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

yole
  • 92,896
  • 20
  • 260
  • 197
22

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

@OneOf(value = ["m", "f"])
BakaWaii
  • 6,732
  • 4
  • 29
  • 41
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
Bao Le
  • 16,643
  • 9
  • 65
  • 68
  • 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) – Ahsan Naseem Dec 21 '20 at 08: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)
balaji
  • 216
  • 2
  • 7