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")
}
相关推荐
学计算机的7 分钟前
Python:OpenCV 教程
开发语言·python
拾忆,想起11 分钟前
Redisson 分布式锁的实现原理
java·开发语言·分布式·后端·性能优化·wpf
大阳12316 分钟前
51单片机4(温度传感器DS18B20)
开发语言·单片机·嵌入式硬件·算法·51单片机
北城以北88881 小时前
Java高级编程--XML
xml·java·开发语言·intellij-idea
冬天vs不冷1 小时前
Java基础(十一):关键字final详解
java·开发语言
HMBBLOVEPDX2 小时前
C++(深拷贝和浅拷贝)
开发语言·c++·浅拷贝和深拷贝
l1t2 小时前
DeepSeek辅助编写的利用quick_xml把xml转为csv的rust程序
xml·开发语言·人工智能·rust·解析器·quick-xml
逐雨~2 小时前
9.11QT作业
开发语言
烟锁池塘柳02 小时前
【已解决,亲测有效】解决使用Python Matplotlib库绘制图表中出现中文乱码(中文显示为框)的问题的方法
开发语言·python·matplotlib
周小码2 小时前
llama-stack实战:Python构建Llama应用的可组合开发框架(8k星)
开发语言·python·llama