使用 kotlin 表达式注解
Using kotlin expression annotations
Kotlin 允许注释表达式。然而,尚不清楚此类注释有何用处以及如何使用它们。
假设在下面的示例中我想检查一下,该字符串包含@MyExpr 注释中指定的数字。这可以实现吗?如何实现?
@Target(AnnotationTarget.EXPRESSION)
@Retention(AnnotationRetention.SOURCE)
annotation class MyExpr(val i: Int) {}
fun someFn() {
val a = @MyExpr(1) "value#1";
val b = @MyExpr(2) "value#2";
}
指定 @Target(AnnotationTarget.EXPRESSION)
只是告诉编译器注释的用户可以将其放置在何处的一种方式。
它不会自己做任何事情,而不是那样做。
例如
@Target(AnnotationTarget.EXPRESSION)
@Retention(AnnotationRetention.SOURCE)
annotation class Something
// compiler will fail here:
@Something class Foo {
// but will succeed here:
val a = @Something "value#1"
}
除非你正在编写一个注解处理器(一个寻找注解并用它们做某事的东西),你的注解只有信息价值。它们只是一个信号对某事的其他开发者(或未来的你)。
@Target(AnnotationTarget.EXPRESSION)
@Retention(AnnotationRetention.SOURCE)
annotation class UglyAndOldCode
val a = @UglyAndOldCode "this is something old and requires refactoring"
如果您想实现您在问题中陈述的内容,您必须创建一个注解处理器来检查标有 MyExpr
的表达式是否符合您指定的条件。
Kotlin 允许注释表达式。然而,尚不清楚此类注释有何用处以及如何使用它们。
假设在下面的示例中我想检查一下,该字符串包含@MyExpr 注释中指定的数字。这可以实现吗?如何实现?
@Target(AnnotationTarget.EXPRESSION)
@Retention(AnnotationRetention.SOURCE)
annotation class MyExpr(val i: Int) {}
fun someFn() {
val a = @MyExpr(1) "value#1";
val b = @MyExpr(2) "value#2";
}
指定 @Target(AnnotationTarget.EXPRESSION)
只是告诉编译器注释的用户可以将其放置在何处的一种方式。
它不会自己做任何事情,而不是那样做。
例如
@Target(AnnotationTarget.EXPRESSION)
@Retention(AnnotationRetention.SOURCE)
annotation class Something
// compiler will fail here:
@Something class Foo {
// but will succeed here:
val a = @Something "value#1"
}
除非你正在编写一个注解处理器(一个寻找注解并用它们做某事的东西),你的注解只有信息价值。它们只是一个信号对某事的其他开发者(或未来的你)。
@Target(AnnotationTarget.EXPRESSION)
@Retention(AnnotationRetention.SOURCE)
annotation class UglyAndOldCode
val a = @UglyAndOldCode "this is something old and requires refactoring"
如果您想实现您在问题中陈述的内容,您必须创建一个注解处理器来检查标有 MyExpr
的表达式是否符合您指定的条件。