Kotlin Basic Tutorial-annotations

Source: Internet
Author: User

Annotation definition Annotations

Annotation Class Fancy
constructor for annotations

can take parameters

Annotation Class Special (Val why:string)
Special ("Example") class Foo {}
using Annotations
@fancy class Foo {
    @fancy fun baz (@fancy foo:int): Int {
        return  1
    }
}
annotations in the main constructor
Class Foo @inject Constructor (dependency:mydependency)
annotations in property visitors
Class Foo {
    var x:mydependency?=null
        @inject Set
}
annotations in lambda expressions
Annotation class Suspendable
val f = @Suspendable {Fiber.sleep (10)}
introduction of annotations in Java

Kotlin can refer directly to annotations in Java.

Import org.junit.Test
Import org.junit.assert.*

class Tests {
    Test fun simple () {
        assertequals (42), GetTheAnswer ())
    }
}

Annotations can be renamed when importing

Import org.junit.Test as Test

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

Specify parameters

Because annotations in Java have no concept of parameters, they are attributes. But the attributes have no order, so when you invoke the annotations, you must mention the names when you pass in the arguments:

Java public
@interface Ann {
    int intvalue ();
    String stringvalue ();
}

Kotlin
Ann (intvalue = 1, stringvalue = "abc") class C

Value parameter

If the definition in Java is a value parameter, then you can use no names:

Public @interface Annwithvalue {
    String value ();
}

Kotlin
annwithvalue ("abc") class C

Array

Kotlin using array instead of arrays

//Java public @interface annwitharrayvalue {string[] value ();}//Kotlin Annwitharrayvalue ("abc", "foo", "Bar") class C 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.