前言:
Kotlin枚举类和Java的枚举类的类型非常相似,具有类的特性,一般会将可枚举的同类型的一组值作为枚举定义,每个枚举常量都是一个对象,枚举常量用逗号分隔。
写法一:
enum class Season{
SPRING,
SUMMER,
AUTUMN,
WINTER
}
结果打印:
println("${Season.SPRING},${Season.SUMMER},${Season.AUTUMN},${Season.WINTER}")
当然还可以使用参数初始化枚举类,且每个枚举类中的常量都可以 .name 拿到名称,.ordinal 拿到位置。代码如下:
enum class Season(var zh: String) {
SPRING("春"),
SUMMER("夏"),
AUTUMN("秋"),
WINTER("冬");
}
println(Season.SUMMER.ordinal.toString() + ":" +Season.SUMMER.name +"->" +Season.SUMMER.zh)
// 打印结果:1:SUMMER->夏
写法二:
在实践过程中,常常想把传入参数转换为对应的枚举值,对应的枚举值转换为传入参数值。比如我想用传入的参数值(Int类型)比较大小,用枚举值(String类型)作为最后的结果展示等等原因。下面举例如下:
/**
Failed 16
Value of ColumnStatus when the download has failed (and will not be retried).
Paused 4
Value of ColumnStatus when the download is waiting to retry or resume.
Pending 1
Value of ColumnStatus when the download is waiting to start.
Running 2
Value of ColumnStatus when the download is currently running.
Successful 8
Value of ColumnStatus when the download has successfully completed.
*/
enum class DownloadStatus(private val value: Int) {
FAILED(16),
PAUSED(4),
PENDING(1),
RUNNING(2),
SUCCESSFUL(8);
fun index(): Int {
return value
}
override fun toString(): String {
return value.toString()
}
companion object {
fun valueOf(value: Int): String? {
return when (value) {
16 -> "FAILED"
4 -> "PAUSED"
1 -> "PENDING"
2 -> "RUNNING"
8 -> "SUCCESSFUL"
else -> null
}
}
}
}
fun main() {
val state = 16
println(DownloadStatus.FAILED.index()) // 16
println(DownloadStatus.valueOf(state)) // FAILED
}
此为app 下载的状态枚举,很显然如果我们想根据传入的参数值去获取到对应的枚举值,使用.ordinal是做不到的。因为传入的参数值不是索引值。
使用写法二可以达到的效果:
- 当接收的值为int类型的表示下载的状态话,我们可以使用DownloadStatus.valueOf(state)方法转换成字符用来显示。
- 当我们想进行区间、大小判断的话,此时使用DownloadStatus.FAILED.index()转换成传入的Int值是更加合适的。
参考资料:
https://blog.csdn.net/u011288271/article/details/108442853
https://docs.microsoft.com/zh-cn/dotnet/api/android.app.downloadstatus
(如果错误,欢迎批评指正,请大佬轻喷)