Moment For Technology

Kotlin - Annotations and enumerations

Posted on Sept. 23, 2022, 2:39 a.m. by Kevin Rodriguez
Category: The back-end Tag: kotlin

annotations

Annotations attach metadata information to the code. Metadata information is defined by the annotation Koltin.metadata.

@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.CLASS)
@SinceKotlin("1.3")
public annotation class Metadata(
 
    @get:JvmName("k")
    val kind: Int = 1.@get:JvmName("bv")
    val bytecodeVersion: IntArray = [],
   
    @get:JvmName("d1")
    val data1: ArrayString = [],
   
    @get:JvmName("d2")
    val data2: ArrayString = [],
    
    @get:JvmName("xs")
    val extraString: String = "".@SinceKotlin("1.2")
    @get:JvmName("pn")
    val packageName: String = "".@SinceKotlin("1.1")
    @get:JvmName("xi")
    val extraInt: Int = 0
)
Copy the code

This @metadata information exists in all class files generated by the Kotlin compiler and is read by the compiler and reflection. For example, the code to declare an annotation using Kotlin looks like this:

annotation class Suspendable
Copy the code

Kotlin uses the keyword Annotation Class to declare annotations. The corresponding Java code is as follows:

@Retention(RetentionPolicy.RUNTIME)
@Metadata( mv = {1, 4, 2}, bv = {1, 0, 3}, k = 1, d1 = {\ "u0000 \ n \ n \ u0002 \ u0018 \ u0002 \ n \ u0002 \ u0010 \ u001b \ n \ u0000 \ \ b u0086 \ u0002 \ u0018 \ u00002 \ u00020 \ u0001B \ u0000 ยจ \ u0006 \ u0002"} , d2 = {"LSuspendable;" , "", "kotlin-one-day.main"} )
public @interface Suspendable {
}
Copy the code

Kotlin's annotations are fully compatible with Java annotations.

The enumeration

Kotlin uses the enum class keyword to declare an enumerated class. Such as:

enum class Direction{
    NORTH, SOUTH, WEST, EAST // Each enumerated constant is an object, separated by commas
}
Copy the code

Compared to string constants, using enumerated classes provides type safety. Enumerated classes have two built-in properties:

public final val name: String
public final val ordinal: Int
Copy the code

Represents the value and subscript position of an enumeration object, respectively. For example, the Direction enumeration class above has the following information for its enumeration object:

fun main(a){
    val north = Direction.EAST
    println(north.name)
    println(north.ordinal)
}
// EAST
/ / 3
Copy the code

Each enumeration is an instance of an enumeration class that can be initialized:

enum class Color(val rgb: Int){
    RED(0xFF0000),
    GREEN(0x00FF00),
    BLUE(0x0000FF)}fun main(a){
    val c = Color.GREEN
    println(c)
    println(c.rgb)
    println(c.name)
}
// GREEN
/ / 65280
// GREEN
Copy the code
Search
About
mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.