一、kotlin中枚举的定义
枚举需要用到两个关键字 enum class,譬如这样
- enum class Color(val r: Int,val g: Int,val b: Int){
- //彩虹色也是一个典故:韦克菲尔德战役
- RED(255,0),ORANGE(255,165,YELLOW(255,255,GREEN(0,BLUE(0,255),INDIGO(75,130),VIOLET(238,130,238);
- fun rgb() = (r * 255 + g) * 256 + b
- }
- fun main() {
- println("RED's RGB value is ${Color.RED.rgb()}")
二、枚举和when的结合
初步使用
- //枚举和when的配合使用
- fun getMnemonic(color: Color): String{
- //when配合枚举使用
- return when(color){
- Color.RED -> "Richard"
- Color.ORANGE -> "Of"
- Color.YELLOW -> "York"
- Color.GREEN -> "Gave"
- Color.BLUE -> "Battle"
- Color.INDIGO -> "In"
- Color.VIOLET -> "Vain!"
- }
- }
如果多个case的结果是一样的,可以通过逗号连接,譬如
- //when的多个case同一个结果的方式
- fun getWarmth(color: Color) = when(color){
- Color.RED,Color.ORANGE,Color.YELLOW -> "warm"
- Color.GREEN -> "neutral"
- Color.BLUE,Color.INDIGO,Color.VIOLET -> "cold"
- }
遇到有case之外其他情况,使用else。用when代替if
- fun mix(c1: Color,c2: Color) =
- when(setOf(c1,c2)){
- setOf(Color.RED,Color.YELLOW) -> Color.ORANGE
- else -> throw Exception("Dirty Color")
- }
使用不带参数的when
- fun mixOptimized(c1: Color,c2: Color) =
- when{
- (c1 == Color.RED&& c2 == Color.YELLOW ||
- c2 == Color.RED&& c1 == Color.YELLOW) -> Color.ORANGE
- else -> throw Exception("Dirty Color")
- }
setOf是将元素加入到Set集合中
when中可通过is判断类型
- fun eval(e: Expr): Int =
- when(e){
- is Num -> e.value
- is Sum -> eval(e.right) + eval(e.left)
- else -> throw IllegalArgumentException("Unknown expression")
- }
when中使用in检查范围
- fun recognize(c: Char) = when(c){
- in '0'..'9' -> "It's a digit!"
- in 'a'..'z',in 'A'..'Z' -> "It's a letter"
- else -> "I don't know what it is."
- }
三、Kotlin中的异常
kotlin中不区分受检异常和
Java中的异常: 受检异常,这种异常必须显式的处理
Kotlin中的异常:不区分受检异常和未受检异常。不用指定函数抛出的异常,而且可以处理也可以不处理异常。
受检异常有个弊端就是:很多时候的异常我们是不需要捕捉的,因为捕捉了也没法处理。
比如BufferReader.close可能会抛出IOException异常,但很多程序对这个异常都不会采取有意义的行动,所以对这个异常的捕获所写的代码就是冗余的代码
当然,它的使用和Java基本一样,try-catch或try-catch-finally块
- //将读取到的字符串类型转化成Int类型
- fun readNumber(reader: BufferedReader): Int?{
- try {
- val line = reader.readLine()
- return Integer.parseInt(line)
- }catch (e: NumberFormatException){
- return null
- }finally {
- reader.close()
- }
- }
其实Kotin中的try关键字也是表达式,所以也可以这么写:
- fun readNumber2(reader: BufferedReader){
- val number = try {
- val line = reader.readLine()
- Integer.parseInt(line)
- }catch (e: NumberFormatException) {
- return
- }
- println(number)
- }
总结
学习Kotlin不仅仅是在学习一种新语言,更是在学习改变习惯思考方式的过程
和Java对比,用Kotin给你带来不一样的思考习惯