Kotlin基礎教程-註解

來源:互聯網
上載者:User

註解 定義註解

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.