一、枚举和when
when可以认为是加强版的switch
枚举类
/**
* 简单枚举
*/
enum class Color { RED, ORANGE, YELLOW }
/**
* 还可以枚举类声明属性和方法
*/
enum class Color(val r: Int, val g: Int, val b: Int) {
RED(255, 0, 0), ORANGE(255, 165, 0), YELLOW(255, 255, 0);//这里是Kotlin中唯一必须使用分号的地方!!!
fun rgb() = (r * 256 + g) * 256 + b
}
使用when处理枚举
/**
* 处理枚举
*/
fun getWord(color: Color) = when (color) {
Color.RED, Color.Orange -> "warm"
Color.YELLOW -> "cold"
else -> throw Exception("Dirty color")
}
/**
* 处理任意对象
*/
fun mix(c1: Color, c2: Color) = when (setOf(c1, c2)) {
setOf(Color.RED, Color.YELLOW) -> Color.ORANGE
setOf(Color.YELLOW, Color.BLUE) -> Color.GREEN
else -> throw Exception("Dirty color")
}
/**
* 不带参数的when
* 不会创建额外对象,但代码不优雅
*/
fun mixOpt(c1: Color, c2: Color) = when {
(c1 == Color.RED && c2 == Color.YELLOW) ||
(c1 == Color.YELLOW && c2 == Color.RED) -> Color.ORANGE
(c1 == Color.YELLOW && c2 == Color.BLUE) ||
(c1 == Color.BLUE && c2 == Color.YELLOW) -> Color.GREEN
else -> throw Exception("Dirty color")
}
一、while和for
Kotlin中并没有对while做加强,所以只需讨论下for
区间和数列
Kotlin中没有常规Java的for循环,作为替代,Kotlin使用了***区间***的概念
区间本质上就是两个值之间的间隔,这两个值通常是数字:一个起始值,一个结束值。使用…运算符来表示区间:
val oneToTen = 1..10//是闭区间
如果能迭代区间中的所有值,这样的区间叫做***数列***
这里还有很多用法,如downTo、until等等,会在后面函数中介绍
关于in和迭代map
/**
* 使用in迭代区间
*/
val binaryReps = TreeMap<Char, String>()
for (c in 'A'..'F') {//创建字符区间
val binary = Integer.toBinaryString(c.toInt()) //将 ASCII 码转化成二进制
binaryReps[c] = binary //根据 key 为c 把 binary 存到 map 中
}
/**
* 使用in迭代区间
*/
val list = arrayListOf("10", "11", "1001")
for ((index, element) in list.withIndex()) {//不用存下标
println("$index : $element")
}
/**
* 使用in检查区间成员
*/
fun isLetter(c: Char) = c in 'a'..'z' || c in 'A'..'Z'
fun isNotDigit(c: Char) = c !in '0'..'9'
这一篇仅仅是介绍这些控制,具体细节会在后面写