Files
kotlin-fork/docs/confluence.jetbrains.com/Kotlin/40702623_Annotations.confluence
T
2012-05-30 14:41:40 +04:00

57 lines
1.5 KiB
Plaintext

In Kotlin, one can attach metadata to declarations in the form of _annotations_. To declare an annotation, put the *annotation* annotation (no pun intended :)) in front of a normal class:
{jet}
annotation class fancy {}
{jet}
(Note that, by convention, annotation classes are named with the lowercase fitst letter; the reason will be clear from the examples below.)
Now we can annotate a declaration or an expression with the new {{fancy}} annotation. In general, one puts square brackets around the annotation name:
{jet}
[fancy] class Foo {
[fancy] fun baz([fancy] foo : Int) : Int {
return [fancy] 1
}
}
{jet}
{note:title=Annotations are under development}{note}
When annotating a declaration (e.g. a function or a class), the square brackets may be omitted:
{jet}
fancy class Foo() {
fancy fun baz(fancy foo: Int) {
return [fancy] 1
}
}
{jet}
Note that square brackets are required for expressions.
Annotation classes may have constructors that take parameters. For example:
{jet}
annotation class special(val why : String)
special("example") class Foo {}
{jet}
As you can see, to pass arguments to an annotation one simply calls its constructor.
On the JVM one can re-use Java annotations:
{jet}
import org.junit.Test
import org.junit.Assert.*
class Tests {
Test fun simple() {
assertEquals(42, getTheAnswer())
}
}
{jet}
If you want your Java annotations to look like modifiers, you can rename them on import:
{jet}
import org.junit.Test as test
class Tests {
test fun simple() {
...
}
}
{jet}