Kotlin topic "Seventeen": enumeration class (enum class)

Foreword: On the way forward, you are not afraid of being blocked by thousands of people, but you are afraid of surrendering yourself; the sail of life is not afraid of strong winds and waves, but you are afraid of your lack of courage.

I. Overview

The most basic use of enumeration classes is to achieve type safety. Enumeration classes are decorated with the enum keyword:

    enum class Direction {
    
    //使用 enum 关键字修饰,在类头 class 前
        NORTH, SOUTH, WEST, EAST
    }

Each enumeration constant is an object, and the enumeration constants are separated by commas.

	fun test() {
    
    
	    Direction.NORTH
        Direction.SOUTH
        Direction.WEST
        Direction.EAST
	}

Enumeration constants can be accessed without instantiating the enumeration class, by 枚举类.常量名calling.

Because every enum is an instance of the enum class, they can be initialized.

    enum class Color(val rgb: Int) {
    
    
        RED(0xFF0000),
        GREEN(0x00FF00),
        BLUE(0x0000FF)
    }

Through the enumeration class constructor, each enumeration has this constructor and needs to initialize the value. For example, the above RED(rgb: Int)needs to initialize the value.

2. Anonymous class for enumeration constants

Enum constants can also declare their own anonymous classes with their corresponding methods, as well as override base methods.

    enum class ConsoleColor(var argb: Int) {
    
    
        RED(0xFF0000) {
    
    
            override fun print() {
    
    //必须重写的
                println("枚举常量 RED")
            }
        },
        WHITE(0xFFFFFF) {
    
    
            override fun print() {
    
    
                println("枚举常量 WHITE")
            }
        },
        BLACK(0x000000) {
    
    
            override fun print() {
    
    
                println("枚举常量 BLACK")
            }
        },//枚举常量之间使用逗号“,”分隔,最后一个常量必须使用分号“;”分隔
        GREEN(0x00FF00) {
    
    
            override fun print() {
    
    
                println("枚举常量 GREEN")
            }
        };

        abstract fun print()//抽象方法,定义在枚举类内部,而且必须在枚举常量后面
    }
  • Commas are used to separate enumeration constants ,. If any members (variables and methods) are defined, semicolons are used ;to separate the constant definition and member definition;
  • An abstract method must be provided, defined inside the enumeration class, and must be behind the enumeration constant.
	fun test() {
    
    
	    ConsoleColor.BLACK
	}

The print data is as follows:

枚举常量 BLACK

Note: Enumeration classes cannot contain nested types other than inner classes.

Third, implement the interface in the enumeration class

Like Java, Kotlin's enum classes can implement interfaces. An enum class can implement an interface, provide a single interface member implementation for all enum constants, or provide a separate interface member implementation for each entry in its anonymous class. This is achieved by adding the interface to the enumeration class declaration. as follows:

    interface ShareListener {
    
    
        fun invite()
    }

    enum class State : ShareListener {
    
    
        NORMAL {
    
    
            override fun invite() {
    
    
                println("实现接口 NORMAL")
            }
        },
        ERROR;

        override fun invite() {
    
    
            println("实现接口 enum")
        }
    }

Kotlin enumeration classes can implement default interface methods, and enumeration class constant members can also implement their own interface methods. The methods implemented by the constant members of the enumeration class are called first, followed by the methods implemented by the enumeration class.

	fun test() {
    
    
	    State.NORMAL
        State.ERROR
	}

The print data is as follows:

实现接口 NORMAL
实现接口 enum

Fourth, the use of enumeration constants

Each enumeration constant has attributes to get its name and position in the enumeration class declaration, including name(枚举常量名)and ordinal(枚举常量位置).

    enum class State {
    
    
        NORMAL,
        ERROR
    }

	fun test() {
    
    
        val normal = State.NORMAL.name //常量名
        val normalIndex = State.NORMAL.ordinal //常量下标

        val error = State.ERROR.name
        val errorIndex = State.ERROR.ordinal
        
        println("枚举常量的使用:name == $normal | ordinal == $normalIndex ")
        println("枚举常量的使用:name == $error | ordinal == $errorIndex ")
	}

The print data is as follows:

枚举常量的使用:name == NORMAL | ordinal == 0 
枚举常量的使用:name == ERROR | ordinal == 1 

Enum classes in Kotlin have composite methods that allow listing defined enum constants and getting enum constants by name. The signatures of these methods are as follows:

EnumClass.valueOf(value: String): EnumClass
EnumClass.values(): Array<EnumClass>

If the specified name does not match any enumeration constant defined in the class, valueOf()the method will throw an IllegalArgumentException; if values()the subscript position does not match, a subscript out of range exception will be thrown.

	fun test() {
    
    
        val normalName = State.valueOf("NORMAL") //指定名称常量
        val errorOrdinal = State.values()[1] //指定下标位置常量

        println("枚举常量的使用:name == $normalName")
        println("枚举常量的使用:name == $errorOrdinal")
	}

The print data is as follows:

枚举常量的使用:name == NORMAL
枚举常量的使用:name == ERROR

Starting from Kotlin 1.1, you can use enumValues<T>()and enumValueOf<T>()combined with generics to access constants in enumeration classes:

	fun test() {
    
    
        val stateName = enumValues<State>().joinToString {
    
     it.name } //打印所有常量
        val stateError = enumValueOf<State>("ERROR") //单个常量

        println("枚举常量的使用:stateName == $stateName")
        println("枚举常量的使用:stateError == $stateError")
	}

The print data is as follows:

枚举常量的使用:stateName == NORMAL, ERROR
枚举常量的使用:stateError == ERROR

The enum constants also implement the Comparable interface, and their natural order is the order in which they are defined in the enum class.

Source address: https://github.com/FollowExcellence/KotlinDemo-master

Pay attention, don't get lost


Well, everyone, the above is the whole content of this article. The people who can see here are all talents .

I am suming, thank you for your support and recognition, your likes are the biggest motivation for my creation, see you in the next article!

If there are any mistakes in this blog, please criticize and advise, thank you very much!

If you want to become an excellent Android developer, here is the knowledge framework you must master , and move towards your dream step by step! Keep Moving!

Guess you like

Origin blog.csdn.net/m0_37796683/article/details/108872675