注解
- 注解
- 注解声明
- 用法
- 构造函数
- Lambdas
- Java注解
注解
注解声明
注解是一种将原数据附加到代码中的方法。声明注解需要在类前面使用annotation
关键字:
//注解
@Target(AnnotationTarget.EXPRESSION, AnnotationTarget.CLASS, AnnotationTarget.FUNCTION, AnnotationTarget.VALUE_PARAMETER)
@Retention(AnnotationRetention.SOURCE)
annotation class TestAnnotation
@TestAnnotation
class TestAnnotationClid {
@TestAnnotation fun baz(@TestAnnotation test:Int):Int{
return (@TestAnnotation 1)
}
}
大多数情况下@标识符是可选的 (就是可带可不带)。只有在注解表达式或本地生命中才必须:
可以注解构造函数
@TestAnnotation constructor(){
}
也可以注解属性访问者
也可以注解访问者属性
@TestAnnotation
class TestAnnotationChild {
@TestAnnotation constructor(){
}
var x:String?=null
@TestAnnotation set
}
构造函数
注解可以有带参数的构造函数
//注解构造函数
annotation class special(val why:String)
@special("example") class TestAnnotationCon{
}
Lambdas
注解也可以用在lambda中,这将会应用到lambda生成的invoke()方法,这对Quasar框架很有用,在这个框架中注解被用来并发控制
//注解在lambda表达式中
annotation class Suspenable
val annotationLambda=@Suspenable{
println("lambda has annotation")
}
Java注解
java注解在kotlin中是完全兼容的:
// Java
public @interface Ann {
int value();
}
// Kotlin
fun foo(ann: Ann) {
val i = ann.value
}