android kotlin基础复习 enum

1、kotlin中,关键字enum来定义枚举类型。枚举类型可以包含多个枚举常量,并且每个枚举常量可以有自己的属性和方法。

2、测试代码:

复制代码
enum class Color{
    RED,YELLOW,BLACK,GOLD,BLUE,GREEN,WHITE
}

inline fun <reified T : Enum<T>> printAllValues() {
    print(enumValues<T>().joinToString { it.name })
}

fun main(args: Array<String>) {
    var color:Color=Color.GOLD

    println(Color.entries.toTypedArray())
    println(Color.valueOf("RED"))
    println("----------------------------")
    println(color.name)
    println(color.ordinal)
    println("----------------------------")
    printAllValues<Color>()
}

3、输出:

复制代码
[Lcom.xxx.myapplication.test.Color;@1a407d53
RED
----------------------------
GOLD
3
----------------------------
RED, YELLOW, BLACK, GOLD, BLUE, GREEN, WHITE
Process finished with exit code 0

4、说明:

color.name:输出值。

color.ordinal:输出索引。

enumValues<T>().joinToString { it.name }:将name,组合起来以逗号隔开输出。

RED, YELLOW, BLACK, GOLD, BLUE, GREEN, WHITE

复制代码
println(Color.entries); 输出上面的数组。

参考:Kotlin 枚举类 | 菜鸟教程

相关推荐
张小姐的猫8 小时前
【MySQL】访问 & 数据流动原理
android·数据库·mysql·adb·1024程序员节
朱涛的自习室11 小时前
212 个需求、22 万行代码:Agent 接管开源项目的 19 天
android·前端·人工智能
灿飞16 小时前
Kotlin与Java虚拟机七:空安全:把十亿美元的错误消灭在类型系统里
java·kotlin
传奇开心果16 小时前
【Flutter踩坑排雷】第3课:const 误用坑|const 错误使用引发 UI 异常与性能损耗
android·flutter
哲鲤16 小时前
AOSP思绎|Android 多媒体:一段视频为什么需要这么多服务
android
阿杰m16 小时前
Android源码第三章:Handler、Looper 与 MessageQueue——一条消息如何入队、唤醒并执行
android
海雅达手持终端PDA19 小时前
巡线、深井、爆管抢修与极寒水网的硬件矩阵怎么配?海雅达水务巡检终端PDA选型指南
android·物联网·5g·集成测试·能源·政务
恋猫de小郭21 小时前
Flutter 开始支持 Jetpack Compose Platform View
android·前端·flutter
三少爷的鞋1 天前
Android 架构七条铁律:架构师真正设计的不是代码,而是秩序
android
xiangxiongfly9151 天前
Android GsonFactory总结
android·gson·gsonfactory