1. 程式人生 > >Kotlin基礎教程-註解

Kotlin基礎教程-註解

註解

定義註解

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 Suspendable
val f = @Suspendable { Fiber.sleep(10) }

引入Java中的註解

kotlin可以直接引用Java中的註解。

import org.junit.Test
import org.junit.Assert.*

class Tests {
    Test fun simple() {
        assertEquals(42, getTheAnswer
()
) } }

註解在匯入時,可以重新命名

import org.junit.Test as test

class Tests {
  test fun simple() {
    ...
  }
}

指明引數

因為Java中的註解,沒有引數的概念,而是屬性。但是屬性有沒有順序,所以你在呼叫註解時,傳入引數時一定要指名道姓:

//Java
public @interface Ann {
    int intValue();
    String stringValue();
}

//kotlin
Ann(intValue = 1, stringValue = "abc"
) class C

值引數

如果Java中的定義是值引數,那麼可以不用指名道姓:

public @interface AnnWithValue {
    String value();
}

//kotlin
AnnWithValue("abc") class C

陣列

kotlin用array代替陣列

// Java
public @interface AnnWithArrayValue {
    String[] value();
}
// Kotlin
AnnWithArrayValue("abc", "foo", "bar") class C