使用 kotlin 表达式注释

ilj*_*jau 5 annotations kotlin

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";
}
Run Code Online (Sandbox Code Playgroud)

Bar*_*ski 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"
}
Run Code Online (Sandbox Code Playgroud)

除非您正在编写注释处理器(即查找注释并使用它们执行某些操作的东西),否则您的注释仅具有信息价值。它们只是向其他开发者(或未来的你)发出的信号。

@Target(AnnotationTarget.EXPRESSION)
@Retention(AnnotationRetention.SOURCE)
annotation class UglyAndOldCode

val a = @UglyAndOldCode "this is something old and requires refactoring"
Run Code Online (Sandbox Code Playgroud)

如果您想实现问题中所述的内容,则必须创建一个注释处理器来检查标记为 的表达式MyExpr是否符合您指定的条件。