Annotation definition Annotations
Annotation Class Fancy
constructor for annotations
can take parameters
Annotation Class Special (Val why:string)
Special ("Example") class Foo {}
using Annotations
@fancy class Foo {
@fancy fun baz (@fancy foo:int): Int {
return 1
}
}
annotations in the main constructor
Class Foo @inject Constructor (dependency:mydependency)
annotations in property visitors
Class Foo {
var x:mydependency?=null
@inject Set
}
annotations in lambda expressions
Annotation class Suspendable
val f = @Suspendable {Fiber.sleep (10)}
introduction of annotations in Java
Kotlin can refer directly to annotations in Java.
Import org.junit.Test
Import org.junit.assert.*
class Tests {
Test fun simple () {
assertequals (42), GetTheAnswer ())
}
}
Annotations can be renamed when importing
Import org.junit.Test as Test
class Tests {
Test fun simple () {
...
}
}
Specify parameters
Because annotations in Java have no concept of parameters, they are attributes. But the attributes have no order, so when you invoke the annotations, you must mention the names when you pass in the arguments:
Java public
@interface Ann {
int intvalue ();
String stringvalue ();
}
Kotlin
Ann (intvalue = 1, stringvalue = "abc") class C
Value parameter
If the definition in Java is a value parameter, then you can use no names:
Public @interface Annwithvalue {
String value ();
}
Kotlin
annwithvalue ("abc") class C
Array
Kotlin using array instead of arrays
//Java public @interface annwitharrayvalue {string[] value ();}//Kotlin Annwitharrayvalue ("abc", "foo", "Bar") class C