Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java annotation implementation to Kotlin

Tags:

kotlin

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.

like image 558
BrokenCranium Avatar asked Feb 21 '26 00:02

BrokenCranium


1 Answers

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.

like image 145
yole Avatar answered Feb 23 '26 22:02

yole