Kotlin基础教程-注解

xiaoxiao2021-02-28  101

注解

定义注解

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
转载请注明原文地址: https://www.6miu.com/read-64377.html

最新回复(0)