40

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

Sign up to request clarification or add additional context in comments.

Comments

24

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

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

Comments

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 Comment

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.