| 定义? 
 声明枚举类使用 enum 关键字。虽然是类但不能创建实例,只能通过类名调用类中定义的枚举常量,每一个枚举常量就是一个该枚举类的实例。 | .oridinal | 枚举常量在类中的索引,从0开始。不存在就报错:ArrayIndexOutOfBoundsException。 |  | compareTo(? ) | A.compareTo( B ) 比较两个枚举常量的索引,A优先返回-1,相等返回0,A落后返回1。 |  | .name toString( ) | 枚举常量的名称。 |  | values( ) valueof( ) | 获取所有枚举常量,返回一个数组。 通过枚举常量的名称获取对应枚举常量。不存在就报错:IllegalArgumentException。 |  | enumValues<T>( ) enumValueOf<T>( ) | 同上,1.1版本起支持以泛型的方式访问。 |  | getDeclaringClass( ) | 通过枚举常量获取枚举类。 | 
 enum class Demo {
    //可以是小写,常量规范用大写
    RED, BLUE, YELLOW, GREEN
}
println(Demo.BLUE.ordinal)  //打印:1
println(Demo.BLUE.name)     //打印:BLUE
//如果 GREEN 不存在,报错:IllegalArgumentException
val aa = Demo.valueOf("GREEN")  //aa就是GREEN这个常量,类型是Demo,还不如就用类名调用
val bb = enumValueOf<Demo>("GREEN") //泛型访问方式
//拿到的是YELLOW,角标超过枚举常量数量报错:ArrayIndexOutOfBoundsException
val cc = Demo.values()[2]    //函数返回数组,因此可直接获取元素
Demo.values().forEach { print("$it,") }    //打印:RED,BLUE,YELLOW,GREEN,
enumValues<Demo>().forEach { print("$it,") }    //泛型访问方式
 枚举常量初始化? 
 每个枚举常量都是该枚举类的实例,可以定义枚举类的主构造进行初始化,枚举常量彼此之间用逗号分隔。声明枚举常量的时候就是在做初始化。可以声明属性或函数,但需要在最后一个枚举常量的后面使用分号 ; 隔开。
 enum class Demo(var str: String, var age: Int) {
    RED("张三", 18),
    BLUE("李四", 22),
    YELLOW("王五", 15);   //后面定义属性或函数需要使用分号隔开
    var gender: Boolean = false
    fun show() = println(str + age)
}
println(Demo.BLUE.str)     //打印:李四
println(Demo.BLUE.age)     //打印:22
Demo.RED.show()     //打印:张三18
println(Demo.RED.gender)    //打印:false
 枚举常量的匿名类 
 枚举常量类体中不管是声明属性还是函数,都需要先在枚举类中定义成open或者abstract,然后去复写。毕竟枚举常量是枚举类的实例。 enum class Demo {
    RED {
        override var str = "RED,str"
        override fun show() { println("RED,show") }
        override fun method() { println("RED,method") }
    };
    abstract fun show()
    open fun method() { println("Demo,method") }
    open var str: String = "Demo,str"
}
 实现接口 
 可以在类中统一进行覆盖,枚举常量自行进行覆盖。 interface AA { fun showAA() }
interface BB { fun showBB() }
enum class Demo : AA, BB {
    RED {
        //覆盖掉统一覆盖,用自己的
        override fun showAA() { println("RED,showBB") }
        //未统一覆盖的,需要自己覆盖
        override fun showBB() { println("RED,showBB") }
    },
    BLUE {
        //未统一覆盖的,需要自己覆盖
        override fun showBB() { println("BLUE,showBB") }
    };
    //统一覆盖
    override fun showAA() { println("DEMO,showAA") }
}
Demo.RED.showAA()   //打印:RED,showBB
Demo.RED.showBB()   //打印:RED,showBB
Demo.BLUE.showAA()  //打印:DEMO,showAA
Demo.BLUE.showBB()  //打印:BLUE,showBB
 一些用法举例enum class Demo{
    BLACK,WHITE,GRAY;
    fun show(){
        when(this.name){
            "BLACK" -> println("BLACK")
            "WHITE" -> println("WHITE")
            "GRAY" -> println("GRAY")
        }
    }
}
 |