一、枚舉和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'
這一篇僅僅是介紹這些控制,具體細節會在後面寫