註解 定義註解
annotation class fancy
註解的建構函式
可以帶參數
annotation class special(val why: String)special("example") class Foo {}使用註解
@fancy class Foo { @fancy fun baz(@fancy foo: Int): Int { return 1 }}主構造器中註解
class Foo @inject constructor (dependency: MyDependency)
屬性訪問者中的註解
class Foo { var x: MyDependency?=null @inject set}lambda運算式中的註解
annotation class Suspendableval f = @Suspendable { Fiber.sleep(10) }引入Java中的註解
kotlin可以直接引用Java中的註解。
import org.junit.Testimport org.junit.Assert.*class Tests { Test fun simple() { assertEquals(42, getTheAnswer()) }}
註解在匯入時,可以重新命名
import org.junit.Test as testclass Tests { test fun simple() { ... }}
指明參數
因為Java中的註解,沒有參數的概念,而是屬性。但是屬性有沒有順序,所以你在調用註解時,傳入參數時一定要指名道姓:
//Javapublic @interface Ann { int intValue(); String stringValue();}//kotlinAnn(intValue = 1, stringValue = "abc") class C
值參數
如果Java中的定義是值參數,那麼可以不用指名道姓:
public @interface AnnWithValue { String value();}//kotlinAnnWithValue("abc") class C
數組
kotlin用array代替數組
// Javapublic @interface AnnWithArrayValue { String[] value();}// KotlinAnnWithArrayValue("abc", "foo", "bar") class C