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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值