Implement (/inherit/~extend) annotation in Kotlin


#1

In Java I have the possibility to “implement” annotations.

Sample Java annotation:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface JavaClassAnno {
  String[] value();
}

Sample Java “implementation”:

class MyAnnotationLiteral 
                  extends AnnotationLiteral<JavaClassAnno> 
                  implements JavaClassAnno { // <--- works in Java
  private String value;

  public MyAnnotationLiteral(String value) {
    this.value = value;
  }
  @Override
  public String[] value() {
    return new String[] { value };
  }
}

Trying to port that to Kotlin doesn’t work as it says that the annotation is final and therefore can not be inherited, i.e. the following will not work:

class MyAnnotationLiteral(private val internalValue: String) 
                 : AnnotationLiteral<JavaClassAnno>(), 
                   JavaClassAnno { // <--- doesn't work in Kotlin (annotation can not be inherited)
  override fun value(): Array<String> {
    return arrayOf(internalValue)
  }
}

How do you “implement/extend” annotations the Kotlin way? Could not find any reason why Kotlin differs in that regard to Java. Any hint how to solve that problem or any sources that tell why it is that way are welcome. This question also has been asked here: https://stackoverflow.com/questions/51608924/implement-inherit-extend-annotation-in-kotlin

Update: Finally I found something regarding this design decision, namely the following issue (while I was opening my own issue for it): Annotations inheritance. Either prohibit or implement correctly. As it seems the decision was to “prohibit” it, even though there are no (visible?) comments, discussions or other sources about that decision.

Added the following issue: https://youtrack.jetbrains.com/issue/KT-25947


#2

https://kotlinlang.org/docs/reference/annotations.html


#4

Sorry, I thought you just want to create a new annotation.
I don’t think it’s possible to implement a koltin annotation in another class since you can’t make it open.


#5

Yeah, I know. “implement” itself is ambiguous, that is why I tried it with “inherit” and “extend”. I also know that annotations are not open (yet?), but I do not know why it was designed that way. There must be a reason for that and that reason should be documented somewhere (sources welcome!). On the other side, it could be a bug as well. I thought “language design” sounds like the place where it could be answered.


#6

I wouldn’t say it’s a bug, it’s more like rare used feature that was not implemented :stuck_out_tongue_closed_eyes:. The best thing to do is probably create a new issue on https://youtrack.jetbrains.com.