Kotlin: how to pass array to Java annotation

2019-04-03 17:53发布

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

All i get is :

Type inference failed. Expected type mismatch:

required: String

found: Array<String>

Kotlin version: 1.1.2-2

3条回答
Explosion°爆炸
2楼-- · 2019-04-03 18:15

As an example from Kotlin docs

@AnnWithArrayMethod(names = arrayOf("abc", "foo", "bar")) class C
查看更多
我命由我不由天
3楼-- · 2019-04-03 18:24

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

查看更多
走好不送
4楼-- · 2019-04-03 18:30

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

@OneOf(value = ["m", "f"])
查看更多
登录 后发表回答