Kotlin集成与测试:从基础到实践
1. 默认目标与注解使用
在Kotlin中,如果添加注解时未指定使用位置,目标将根据注解上指定的目标来选择。例如,以下自定义注解:
@Target(AnnotationTarget.PROPERTY_GETTER)
annotation class ColorRes
这个注解只能应用于属性的getter方法,不能用于其他目标。因此,下面的代码无法编译:
class ViewModel( @ColorRes val resId:Int ) // will not compile
但如果指定了 get 使用位置,代码就能正常编译:
class ViewModel( @get:ColorRes val resId:Int )
如果注解声明中不包含 @Target 注解,以下目标是适用的:
- class
- property
- field
- local_variable
- value_parameter
- constructor
- function
- property_getter
- property_setter
利用这些目标来定义自定义注解,可以提高
超级会员免费看
订阅专栏 解锁全文
979

被折叠的 条评论
为什么被折叠?



