使用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";
}
lybgg121 回答:使用Kotlin表达式注释

指定@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的表达式是否符合您指定的条件。

本文链接:https://www.f2er.com/3107492.html

大家都在问