Kotlin基础之枚举和when

 

1.申明枚举类

package com.zhoujian.kotlindemo.shaps

enum class Color {
    RED,YELLOW,GREEN,WHITE
}

Kotlin申明美枚举类用了enum、class两个关键字

Java只有了一个enum一个关键字

可以给枚举类声明属性和方法

package com.zhoujian.kotlindemo.shaps

enum class Color(val r: Int, val g: Int, val b: Int) {

    RED(256, 0, 0), YELLOW(255, 255, 0), GREEN(0, 255, 0);

    fun rgb() = (r * 256 + g) * 256 + b
}

这是Kotlin中唯一必须使用分号的地方

2.使用when处理枚举类

Java中的switch对应Kotlin中的when


    fun getMemeryColor(color: Color) = when (color) {
        Color.RED -> "red"
        Color.YELLOW -> "yellow"
        Color.GREEN -> "green"
    }

合并多个选项

  fun getWarm(color: Color) = when (color) {
        Color.RED, Color.YELLOW -> "warm"
        Color.GREEN -> "other"
    }

3.在when中使用任意对象

fun mix(c1: Color, c2: Color) = when (setOf(c1, c2)) {
        setOf(Color.RED, Color.YELLOW) -> Color.YELLOW
        else ->throw Exception("error")

    }

Kotlin标准函数库:setOf可以创建出一个set

4.使用层叠对表达式求值

package com.zhoujian.kotlindemo.inter

interface Expr

申明一个接口 

package com.zhoujian.kotlindemo.inter

class Num(val value:Int):Expr

 实现接口

package com.zhoujian.kotlindemo.inter

class Sum(val left:Expr,val right:Expr):Expr
 fun eval(e: Expr): Int {
        if (e is Num) {
            val n = e as Num
            return n.value
        }
        if (e is Sum) {
            return eval(e.right) + eval(e.left)
        }
        throw Exception("error")
    }

is是用来判断一个变量是否是某种类型,类似于Java 的instanceOf

使用as关键字来表示特定类型的显示转换

5.使用when代替if


    fun evalwhen(e: Expr): Int =
            when (e) {
                is Num -> e.value
                is Sum -> evalwhen(e.right) + evalwhen(e.left)
                else -> throw Exception("error")
            }

6. 代码块作为if和when的分支

 fun evalLog(e: Expr): Int = when (e) {
        is Num -> {
            println("num:${e.value}")
            e.value
        }
        is Sum -> {
            val left = evalLog(e.left)
            val right = evalLog(e.right)
            println("sum:$left+$right")
            left + right
        }
        else -> throw Exception("error")
    }

if和when都可以使用代码块作为分支体,这种情况下,代码块中的最后一个表达式就是结果

发布了272 篇原创文章 · 获赞 68 · 访问量 40万+

猜你喜欢

转载自blog.csdn.net/u014005316/article/details/90105291