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")
}
相关推荐
毕设源码-邱学长4 小时前
【开题答辩全过程】以 基于Java的学校住宿管理系统的设计与实现为例,包含答辩的问题和答案
java·开发语言
rookieﻬ°5 小时前
PHP框架漏洞
开发语言·php
炸膛坦客6 小时前
单片机/C/C++八股:(二十)指针常量和常量指针
c语言·开发语言·c++
兑生6 小时前
【灵神题单·贪心】1481. 不同整数的最少数目 | 频率排序贪心 | Java
java·开发语言
炸膛坦客7 小时前
单片机/C/C++八股:(十九)栈和堆的区别?
c语言·开发语言·c++
零雲7 小时前
java面试:了解抽象类与接口么?讲一讲它们的区别
java·开发语言·面试
Jay_Franklin7 小时前
Quarto与Python集成使用
开发语言·python·markdown
2401_831824968 小时前
代码性能剖析工具
开发语言·c++·算法
是wzoi的一名用户啊~8 小时前
【C++小游戏】2048
开发语言·c++
Sunshine for you9 小时前
C++中的职责链模式实战
开发语言·c++·算法