Как каждый создает @interface
в Scala? Я честно чувствую себя глупым, прося, что вопрос, но я не могу найти синтаксис для этого нигде. Я знаю, что можно использовать их, но как Вы на самом деле определяете новые в Scala?
Java:
public @interface MyAnnotation { }
Scala:
???
Этот ответ основан на Scala 2.8.
// Will be visible to the Scala compiler, but not in the class file nor at runtime.
// Like RetentionPolicy.SOURCE
final class MyAnnotation extends StaticAnnotation
// Will be visible stored in the annotated class, but not retained at runtime.
// This is an implementation restriction, the design is supposed to support
// RetentionPolicy.RUNTIME
final class MyAnnotation extends ClassfileAnnotation
Для получения полной информации см. Раздел 11 «Пользовательские аннотации» в Справочнике Scala См., Например: @tailrec .
ОБНОВЛЕНИЕ Лучше всего сказано в предупреждении компилятора:
>cat test.scala
final class MyAnnotation extends scala.ClassfileAnnotation
@MyAnnotation
class Bar
>scalac test.scala
test.scala:1: warning: implementation restriction: subclassing Classfile does not
make your annotation visible at runtime. If that is what
you want, you must write the annotation class in Java.
final class MyAnnotation extends scala.ClassfileAnnotation
Если вы хотите создать аннотацию в Scala, вы должны смешать черты StaticAnnotation
или ClassAnnotation
. Пример кода:
class MyBaseClass {}
class MyAnnotation(val p:String) extends MyBaseClass with StaticAnnotation {}
@MyAnnotation("AAA")
class MyClass{}