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 attach metadata information to the code. Metadata information is defined by the annotation Koltin.metadata.

public annotation class Metadata(
    val kind: Int = 1.@get:JvmName("bv")
    val bytecodeVersion: IntArray = [],
    val data1: ArrayString = [],
    val data2: ArrayString = [],
    val extraString: String = "".@SinceKotlin("1.2")
    val packageName: String = "".@SinceKotlin("1.1")
    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:

@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
/ / 3
Copy the code

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

enum class Color(val rgb: Int){
    BLUE(0x0000FF)}fun main(a){
    val c = Color.GREEN
/ / 65280
Copy the code
About (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.