Kotlin学习笔记(二)—— when

when 语句是 Java中 switch 的强化版,它对一个值进行判断,直到匹配到或者没有可匹配的值。

有参数 when
when单值匹配

当 when 语句没有返回值时,就不必要列举出所有的可能性,如:

fun whenFun(x: Int) {
    when(x) {
        0 -> "less than 2"
        1 -> "less than 2"
    }
}

上面的 whenFun函数并没有声明返回值,所以只列举了0和1这两种情况IDE也没有报错。但是如果声明了返回值,那就必须要列举出所有的可能性,以便能处理所以的情况。下面是有返回值的情况:

fun whenFun(x: Int): String {
    return when(x) {
        0 -> "less than 2"
        1 -> "less than 2"
        else -> "others"
    }
}

// 或者以下写法

fun whenFun(x: Int): String {
    val result =  when(x) {
        0 -> "less than 2"
        1 -> "less than 2"
        else -> "others"
    }
    return result
}

声明了返回值必须要列出所有情况,上面函数其他情况用 else 处理了。

when分支合并

when分支还可以合并,例如上面的例子?可以写成

fun whenFun(x: Int): String {
    return when(x) {
        0, 1 -> "less than 2"
        else -> "others"
    }
}
匹配函数

when语句的分支不仅仅是单个值,还可以是一个函数。下列函数输入一个x,判断函数Math.abs(x)的返回值是否和x相等。

fun getAbs(x: Int) = {
    when (x) {
        Math.abs(x) -> true
        else -> false
    }
}

>> println(getAbs(-5))
() -> kotlin.Boolean // 直接用 = 号返回的是返回值的类型
fun getAbs(x: Int): Boolean {
    return when (x) {
        Math.abs(x) -> true
        else -> false
    }
}

>> println(getAbs(-5))
false // 有具体返回值类型则返回的是具体的类型
匹配区间
fun isInRange(x: Char): Boolean {
    return when (x) {
        in 'a'..'z' -> true
        else -> false
    }
}

>> println(isInRange('g'))
true

使用了 in 关键字,判断字符x是否在字符区间内,区间也可用数字区间,数组、集合等。

// 数字区间
fun isInRange(x: Int): Boolean {
    return when (x) {
        in 1..10 -> true
        else -> false
    }
}

>> println(isInRange(20))
false
// 集合区间
fun isInRange(x: Int): Boolean {
    return when (x) {
        in listOf(1, 2, 3, 4, 5) -> true
        else -> false
    }
}

>> println(isInRange(4))
true
// 数组区间
fun isInRange(x: Int): Boolean {
    return when (x) {
        in arrayOf(1, 2, 3, 4, 5) -> true
        else -> false
    }
}

>> println(isInRange(4))
true
类型匹配

判断输入的类型是否是某类型

fun isString(x: Any): Boolean {
    return when (x) {
        is String -> true
        else -> false
    }
}

>> println(isString("Kotlin"))
true
无参数when

无参数when类似多分支的 if-else。

fun compareInt(x: Int, y: Int): String {
    return when {
        x > y -> "$x is more than $y"
        else -> "$x is less than $y"
    }
}

>> println(compareInt(5, 10))
5 is less than 10

**注意:**无参数when,when关键字后面不带括号,分支中的 -> 左右都是一个表达式,左边表达式为 Boolean类型,表达式的结果为true时才会触发 -> 右边的结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值