Android开发经验谈Android开发程序员

Kotlin 枚举和 when

2017-11-10  本文已影响233人  WangJie0822
image.png

前言


枚举类


这个例子中向你展现了 Kotlin 中唯一必须使用分号的地方:如果要在枚举类中定义方法,就要使用分号把枚举常量类别和方法声明分隔开。

when


fun getString(color: Color) = 
    when(color) {
        Color.RED -> "red"
        Color.ORANGE -> "orange"
        Color.YELLOW -> "yellow"
        Color.GREEN -> "green"
        Color.BLUE -> "blue"
        Color.INDIGO -> "indigo"
        Color.VIOLET -> "violet"
    }
fun getString(color: Color) = 
    when(color) {
        Color.RED, Color.ORANGE, Color.YELLOW -> "warm"
        Color.GREEN, Color.BLUE, Color.INDIGO, Color.VIOLET -> "cold"
    }
fun <N: Number> round(num: N): Int { // 使用泛型,所有基本数值类型都是继承 Number
    return when(num) {
        is Float -> (this + 0.5F).toInt() // 是浮点类型,进行四舍五入计算
        is Double -> (this + 0.5).toInt()
        else -> num.toInt() // 上面的都不符合,执行 else 分支
    }
}
fun <N: Number> round(num: N): Int {
    return when {
        is Float -> (this + 0.5F).toInt()
        is Double -> (this + 0.5).toInt()
        else -> num.toInt() 
    }
}

智能转换


/* Java */
Drawable drawable = iv.getDrawable();
if(drawable instanceof AnimationDrawable) { // 使用 instanceof 判断是否是动画类型
    AnimationDrawable anim = (AnimationDrawable) drawable; // 强制类型转换
    anim.start();
}

/* Kotlin */
val drawable  = iv.drawable
if(drawable is AnimationDrawable) { // 使用 is 判断是否是动画类型
    drawable.start() // 判断成功自动类型转换
}

在有需要的时候也可以使用 as 来进行显示转换
val drawable = iv.drawable as AnimationDrawable

最后


上一篇 下一篇

猜你喜欢

热点阅读