Kotlin 学习笔记(二) if、when、is 、枚举 和 异常

前言
本文章只是用于记录学习,所以部分地方如果有错误或者理解不对的地方,麻烦请指正。

Kotlin 学习笔记 (一)

1.枚举

enum class color{
    RED,
    GREEN,
    BLUE
}

   在kotlin 中声明枚举类需要添加 enum class 枚举名,enum 算是一个 软关键词,所以不需搭配 class ,和java 中 枚举类是值的列表 不一样,kotiln 是可以给枚举添加 属性和方法的。如下段代码,

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(){
        println(r+g+b)
    }
}

// main 方法中引用
 color.BLUE.rgb()
 

   上图 枚举类的构造方法和属性的时候和常规类 是一样的,所以声明 枚举类常亮的时候就必须输入属性值,上段代码 也是 介绍到了 kotlin 中少数需要 分开的地方,用于将 常亮列表 和 方法 的分开。

2.when循环

   结合上边我们学到的 枚举 我们结合when 学习一下基础使用

fun getColor(color :Color){
    when(color){
        Color.BLUE -> println("this is blue")
        Color.RED -> println("this is RED")
        Color.GREEN -> println("this is GREEN")
    }
}

// main 调用
getColor(Color.GREEN)

   如上段代码,我们使用when 来判断,但是 我们不用每一句后边都添加 break 来代表结束,kotlin 中如果 某一个分支 匹配成功,就不会进入到其他的分支,当然也可以 多条件,如下

fun getColor(color :Color){
    when(color){
        Color.BLUE ,Color.RED -> println("this is blue or red")
        Color.GREEN -> println("this is GREEN")
    }
}

   如果有 两到多个条件,条件之间可以用 逗号分隔。当然kotlin中也可以使用 任意对象对接使用

fun maxColor(color1 :Color ,color2 :Color){
    when(setOf(color1 ,color2)){
        setOf(Color.BLUE ,Color.RED) -> println("this is blue or red")
        setOf(Color.BLUE ,Color.GREEN) -> println("this is GREEN")
        else -> println("this is not max color")
    }
}

   when 检查 分支是否符合条件,如果都不符合就走 else ,当然这样比较每次都会创建 一些set 对象,我们也可以 when中 不添加参数,直接比较 color1 和 color 2 是否一样,但是代码更多,有一点不太好理解。

3.if

在上一张主要用到了 if 和 if的缩写形式,如果if 返回单句表达式。

fun max(a: Int, b: Int): Int {
    if (a > b) {
        return a
    } else {
        return b
    }
}

// 单句表达式
fun getResult(a: Int, b: Int) = a + b

// 加上 if
fun getMaxResult(a: Int, b: Int) = if(a>b) a else b

4.for in 区间

  1. kotlin 中的for 循环相较于 java 更加的简洁
// in操作符可以判断是否arg是否在args里面
for (arg in args) { 
    print(arg)
} 

// 另外的一种姿势
for (i in args.indices) {
    print(args[i])
}

   上段代码中我们使用了 in ,接下在 我们主要看下 in 的搭配使用和每种使用标识的具体意思

//  检测某个数字是否在指定区间外
if (x in 1..y-1) { // x是否在 1到y-1的范围 
    print("OK")
}
for (i in 1..100) { ... }  //  1到100范围
for (i in 1 until 100) { ... } // 半开范围,不包括100,相当于[1,100)
for (x in 2..10 step 2) { ... } // 每次加2,内容为 x , x+2 ,x+4 ...
for (x in 10 downTo 1) { ... } // 倒序

   如果让我们用 kotlin 写 1 到100 倒序的所有 偶数,我们就可以这样写

for(i in 100 downTo 1 step 2){
    prinln(....)
}

   使用lambda 表达式来过滤(filter)和映射(map)集合

fun main(args: Array<String>) {
    val langs = listOf("C", "C++", "Java", "Python", "JavaScript")

	// startsWith 给定的字串和自己定义的字串相比较,看是否是前缀相同
    langs.filter { it.startsWith("C") }  
            .sortedBy { it }
            .map { it.toUpperCase() }
            .forEach { println(it) }
}

上面代码 引用了超纲的 顺序操作符

reversed() : 反序。即和初始化的顺序反过来。
sorted() : 自然升序。
sortedBy{} : 根据条件升序,即把不满足条件的放在前面,满足条件的放在后面
sortedDescending() : 自然降序。
sortedByDescending{} : 根据条件降序。和sortedBy{}相反

6. while

   kotlin 中的 while 和java 是类似的

while (i < args.size) {
    print(args[i++])
}  

学习完上边的 if、is、 when 我们来尝试 写一个 方法、

fun main(args: Array<String>) {
    println(descript("hello"))
}

fun descript(obj: Any): String = when (obj) {
    1 -> "one"
    "hello" -> "hello word"
    is Long -> "long type"
    !is String -> "is not String"
    else -> {
        "unknown type"
    }
}

7. 异常

   kotlin 中的 异常 和 java 中的异常是差不多的,不过java 中需要new ,而kotlin中 都不需要new,直接 throw IllegalArgumentException(“err”) , kotlin 中的 throw 算是一种表达式,可以在另外的表达式中使用。

fun maxColor(color1 :Color ,color2 :Color){
    when(setOf(color1 ,color2)){
        setOf(Color.BLUE ,Color.RED) -> println("this is blue or red")
        setOf(Color.BLUE ,Color.GREEN) -> println("this is GREEN")
        else ->  throw IllegalArgumentException("err")
    }
}

   java 和 kotlin 中的 try catch finally 适用方式是一样的,不过在kotlin中,try catch 为一种表达式。

fun maxColor(color1 :Color ,color2 :Color) {
    var str = try {
        when(setOf(color1 ,color2)){
            setOf(Color.BLUE ,Color.RED) -> "this is blue or red"
            setOf(Color.BLUE ,Color.GREEN) -> "this is GREEN"
            else ->  throw IllegalArgumentException("err")
        }
    } catch (e:IndexOutOfBoundsException){
        null
    }
    print(str)
}

   从上边代码可以看到,try 作为 表达式 可以将值赋值给一个变量的,如果when 比较分支 成功 就会打印对应的 字符串,如果都没有就抛出异常,catch 捕捉异常,返回 null。

Kotlin 学习笔记 (三)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值