Kotlin基础——枚举、When、in、for

枚举

声明只有值的枚举

复制代码
enum class Color {
    RED, GREEN, BLUE
}

此外还可以增加属性和方法,如果需要在枚举类中定义方法,要使用分号把枚举常量列表和方法定义分开,这也是Kotlin唯一必须使用分号的地方

复制代码
enum class Color(val r: Int, val g: Int, val b: Int) {
    RED(255, 0, 0), GREEN(0, 255, 0), BLUE(0, 0, 255);

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

When

可使用多行表达式函数体

复制代码
fun getRgb(color: Color) =
    when (color) {
        Color.RED -> "255,0,0"
        Color.GREEN -> "0, 255, 0"
        Color.BLUE -> "0, 0, 255"
    }

上面只会匹配对应分支,如果需要多个值合并,则使用逗号隔开

复制代码
fun getRgb(color: Color) =
    when (color) {
        Color.RED, Color.GREEN -> "255,255,0"
        Color.BLUE -> "0, 0, 255"
    }

when可以使用任何对象,如下使用set进行判断(不分顺序)

复制代码
fun getRgb(c1: Color, c2: Color) =
    when (setOf(c1, c2)) {
        setOf(Color.RED, Color.GREEN) -> "255,255,0"
        setOf(Color.GREEN, Color.BLUE) -> "0,255,255"
        else -> throw Exception("none")
    }

如果没有给when提供参数,则分支条件为布尔表达式

复制代码
fun getRgb(c1: Color, c2: Color) =
    when {
        (c1 == Color.RED && c2 == Color.GREEN) || (c1 == Color.GREEN && c2 == Color.RED) -> "255,255,0"
        (c1 == Color.GREEN && c2 == Color.BLUE) || (c1 == Color.BLUE && c2 == Color.GREEN) -> "0,255,255"
        else -> throw Exception("none")
    }

使用When优化if

对于如下类结构

复制代码
interface Expr
class Num(val value: Int) : Expr
class Sum(val left: Int, val right: Int) : Expr

计算加法时,使用if如下,代码块中的最后表达式即为返回值,但不适用于函数(需要显示return)

复制代码
fun eval(e: Expr): Int =
    if (e is Num) {
        e.value
    } else if (e is Sum) {
        eval(e.left) + eval(e.right)
    } else {
        throw IllegalArgumentException("")
    }

可使用when对其进行优化

复制代码
fun eval(e: Expr): Int =
    when (e) {
        is Num -> {
            e.value
        }
        is Sum -> {
            eval(e.left) + eval(e.right)
        }
        else -> {
            throw IllegalArgumentException("")
        }
    }

in

可使用in判断一个值是否在一个区间/集合内,反之使用 !in

复制代码
fun isNum(c: Char) = c in '0'..'9'
fun isNotNum(c: Char) = c !in '0'..'9'

println("Kotlin" in setOf("Java", "C"))

可用于when中进行判断

复制代码
fun recognize(c: Char) = when (c) {
    in '0'..'9' -> "digit"
    in 'a'..'z' -> "letter"
    else -> "not know"
}

可用于比较任何实现了Comparable接口的对象,如下比较字符串将按照字母表顺序

复制代码
println("Kotlin" in "Java".."Z")

for

如判断奇偶数的函数

复制代码
fun isEven(i: Int) = when {
    i % 2 == 0 -> "偶数"
    else -> "奇数"
}

for循环可使用区间表示两个值之间的间隔,如下分别表示1,10、[1,10)

复制代码
for (i in 1..10) {
    print(i)
    print("是")
    println(isEven(i))
}

for (i in 1 until 10) {
    print(i)
    print("是")
    println(isEven(i))
}

如果需要反向,且设置步长(可为负数),可使用

复制代码
for (i in 10 downTo 1 step 2) {
    print(i)
    print("是")
    println(isEven(i))
}

还可以用for遍历集合

复制代码
val chartBinary = TreeMap<Char, String>()

for (c in 'A'..'D') {
    val binary = Integer.toBinaryString(c.toInt())
    chartBinary[c] = binary;
}

for ((chat, binary) in chartBinary) {
    println("$chat = $binary")
}

如果需要跟踪下标,可使用withIndex()

复制代码
val list = arrayListOf("A", "B")
for ((index, element) in list.withIndex()) {
    println("$index: $element")
}
相关推荐
逗脑IDE3 小时前
零基础学ESP32:RFID无线射频卡——让ESP32拥有“刷卡“能力!
开发语言·网络·人工智能·python·esp32·硬件开发
小师兄吃牛肉3 小时前
C语言篇:内联函数
c语言·开发语言
yuniko-n3 小时前
【Java】字符串相关坑点
java·开发语言·python
jimy14 小时前
虚函数vtable,链接时看到构造函数,linker把符号地址写入vtable(三)
开发语言·c++
ss2734 小时前
AI全栈实战 | 3.3-02 Python 并发:有 GIL 为什么还用多线程,asyncio 和 JS 事件循环同源不同味
开发语言·javascript·python
菜鸟~noob2334 小时前
【电子战】第20篇:凸优化与对数障碍法【含matlab代码】
开发语言·matlab
Wang's Blog4 小时前
Java框架 SpringCloud 快速入门: 服务拆分案例 Demo
java·开发语言·spring cloud
小小龙学IT4 小时前
Python SQLAlchemy 2.0 深度解析:从 Core 到 ORM 的数据访问双引擎
开发语言·数据库·python
2601_962885724 小时前
如何用 Python 计算 ROC 变动率指标做动量分析?
开发语言·python·算法
潼心1412o5 小时前
C++初阶(长期更新)第9讲:string(上)
开发语言·c++