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")
}
相关推荐
Kapaseker17 小时前
实战 Compose 中的 IntrinsicSize
android·kotlin
A0微声z3 天前
Kotlin Multiplatform (KMP) 中使用 Protobuf
kotlin
alexhilton3 天前
使用FunctionGemma进行设备端函数调用
android·kotlin·android jetpack
lhDream4 天前
Kotlin 开发者必看!JetBrains 开源 LLM 框架 Koog 快速上手指南(含示例)
kotlin
RdoZam4 天前
Android-封装基类Activity\Fragment,从0到1记录
android·kotlin
Kapaseker4 天前
研究表明,开发者对Kotlin集合的了解不到 20%
android·kotlin
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1234 天前
matlab画图工具
开发语言·matlab
dustcell.4 天前
haproxy七层代理
java·开发语言·前端
norlan_jame4 天前
C-PHY与D-PHY差异
c语言·开发语言