1.申明枚舉類
package com.zhoujian.kotlindemo.shaps
enum class Color {
RED,YELLOW,GREEN,WHITE
}
Kotlin申明美枚舉類用了enum、class兩個關鍵字
Java只有了一個enum一個關鍵字
可以給枚舉類聲明屬性和方法
package com.zhoujian.kotlindemo.shaps
enum class Color(val r: Int, val g: Int, val b: Int) {
RED(256, 0, 0), YELLOW(255, 255, 0), GREEN(0, 255, 0);
fun rgb() = (r * 256 + g) * 256 + b
}
這是Kotlin中唯一必須使用分號的地方
2.使用when處理枚舉類
Java中的switch對應Kotlin中的when
fun getMemeryColor(color: Color) = when (color) {
Color.RED -> "red"
Color.YELLOW -> "yellow"
Color.GREEN -> "green"
}
合併多個選項
fun getWarm(color: Color) = when (color) {
Color.RED, Color.YELLOW -> "warm"
Color.GREEN -> "other"
}
3.在when中使用任意對象
fun mix(c1: Color, c2: Color) = when (setOf(c1, c2)) {
setOf(Color.RED, Color.YELLOW) -> Color.YELLOW
else ->throw Exception("error")
}
Kotlin標準函數庫:setOf可以創建出一個set
4.使用層疊對表達式求值
package com.zhoujian.kotlindemo.inter
interface Expr
申明一個接口
package com.zhoujian.kotlindemo.inter
class Num(val value:Int):Expr
實現接口
package com.zhoujian.kotlindemo.inter
class Sum(val left:Expr,val right:Expr):Expr
fun eval(e: Expr): Int {
if (e is Num) {
val n = e as Num
return n.value
}
if (e is Sum) {
return eval(e.right) + eval(e.left)
}
throw Exception("error")
}
is是用來判斷一個變量是否是某種類型,類似於Java 的instanceOf
使用as關鍵字來表示特定類型的顯示轉換
5.使用when代替if
fun evalwhen(e: Expr): Int =
when (e) {
is Num -> e.value
is Sum -> evalwhen(e.right) + evalwhen(e.left)
else -> throw Exception("error")
}
6. 代碼塊作爲if和when的分支
fun evalLog(e: Expr): Int = when (e) {
is Num -> {
println("num:${e.value}")
e.value
}
is Sum -> {
val left = evalLog(e.left)
val right = evalLog(e.right)
println("sum:$left+$right")
left + right
}
else -> throw Exception("error")
}
if和when都可以使用代碼塊作爲分支體,這種情況下,代碼塊中的最後一個表達式就是結果