56.枚举

作者: 写代码的向日葵 | 来源:发表于2019-10-05 01:08 被阅读0次

    1.简单用法

    fun main(args: Array<String>) {
        println(Week.Monday)
        Week.values().forEach {
            println(it)
        }
        todo(Week.Wednesday)
    }
    
    fun todo(week: Week) {
        when (week) {
            in Week.Monday..Week.Friday -> println("上班")
            else -> println("休息")
        }
    }
    
    enum class Week {
        Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
    }
    

    运行结果如下:


    image.png

    2.高级用法

    fun main(args: Array<String>) {
        println(Color.READ.r)
    }
    
    //枚举三元色
    //红 r 255 g 0 b 0
    //绿r 0 g 255 b 0
    //蓝 r 0 g 0 b 255
    enum class Color(val r: Int, val g: Int, val b: Int) {
        READ(255, 0, 0), GREEN(0, 255, 0), BLUE(0, 0, 255)
    }
    
    • 枚举也可以定义构造函数

    相关文章

      网友评论

        本文标题:56.枚举

        本文链接:https://www.haomeiwen.com/subject/pklepctx.html