3

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.

1 Answer 1

5

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.

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

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.