Reputation: 33
I am trying to replicate the implementation of @Age constraint(found it on online) from Java to Kotlin, I copied the java code base and used the IDE to convert it Kotlin code.
Java code
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Repeatable(Age.List.class)
@Documented
@Constraint(validatedBy = { })
public @interface Age {
String message() default "Must be greater than {value}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
long value();
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
@interface List {
Age[] value();
}
}
Corresponding Kotlin code generated by Intellij
@Target(AnnotationTarget.*)
@Retention(RUNTIME)
@Repeatable(Age.List::class)
@Documented
@Constraint(validatedBy = arrayOf())
annotation class Age(
val value: Long,
val message: String = "Must be greater than {value}",
val groups: Array<KClass<*>> = arrayOf(),
val payload: Array<KClass<out Payload>> = arrayOf()) {
@Target(AnnotationTarget.FUNCTION,
AnnotationTarget.PROPERTY_GETTER,
AnnotationTarget.PROPERTY_SETTER,
AnnotationTarget.FIELD,
AnnotationTarget.ANNOTATION_CLASS,
AnnotationTarget.CONSTRUCTOR,
AnnotationTarget.VALUE_PARAMETER,
AnnotationTarget.TYPE)
@Retention(RUNTIME)
@Documented
annotation class List(vararg val value: Age)
}
The Kotlin code results in error stating "Members are not allowed in annotation class". Does moving the annotation class List out from Age should resolve the issue? Is there any other way to implement an annotation class within another one?
Thank You.
Upvotes: 3
Views: 1960
Reputation: 97128
Yes, you need to move List
out of Age
. The restriction on having nested classes inside annotations will very likely be removed in a future version of Kotlin; it's more of a design oversight than an essential issue.
Upvotes: 5