I want to annotate a property with the annotation ...
# getting-started
v
I want to annotate a property with the annotation
Copy code
public annotation class XmlBefore(vararg val value: String)
so I use
Copy code
@XmlBefore("display-name"),
but I get
Copy code
java.lang.ClassCastException: java.lang.String cannot be cast to [Ljava.lang.String;
😞 Any way to mitigate this? Especially with Kotlin 1.7.10 which I'm pinned to due to Gradle version. Actually, the error comes from the static initializer of the generated serializer where this annotation is used. And when giving two arguments it does not even compile.
r
I don't think annotations support varargs: https://kotlinlang.org/docs/annotations.html#constructors My guess is since under the covers the vararg declaration gets translated to an array, it doesn't error, but the annotation processor fails to handle the usage syntax.
v
If an annotation that is written in Java has an array-typed parameter, it is even provided as vararg in Kotlin: https://kotlinlang.org/docs/annotations.html#arrays-as-annotation-parameters So I'd really wonder if native varargs are not supported. Besides that the annotation is from xmlutil lib, not mine, so I guess somehow somewhere it works already.
r
Interesting, guess I'm wrong then.
r
Apologies if too obvious, but I guess you’ve tried
@XmlBefore(arrayOf(“display-name”))
v
What I tried is
@XmlBefore(["display-name"])
as I assume
arrayOf
is problematic due to needing fixed values for annotation properties. And with that it complained that I need to give
String
, not
Array<String>
Unfortunately this seems to be different in Kotlin from Java where you can also give an array directly to a varargs method.
And no apology needed, asking the obvious often leads to the solution already