枚举
声明只有值的枚举
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")
}