kotlind day2

Kotlin中的when表达式对标Java中的Switch Case,同时它的功能更为强大,更为灵活和更具表现力


1.基本的 when 表达式语法


注意when表达式中,没有breakcontinue,同时使用 -> 箭头函数指向代码块

fun main(args: Array<String>) {
    val x = 2
    when (x) {
        1 -> println("Value of x is 1")
        2 -> println("Value of x is 2")
    }
}

输出:

Value of x is 2


2. when 表达式的默认分支

当我们的需要的分支枚举完毕,可以使用 else 指向默认分支

fun main(args: Array<String>) {
    val x = 100
    when (x) {
        1 -> println("Value of x is 1")
        2 -> println("Value of x is 2")
        else -> print("Value of x is $x")
    }
}

输出:

Value of x is 100


3. when 表达式中使用范围表达式

fun main(args: Array<String>) {
    val x = 15
    val numbersList = arrayListOf(11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
    when (x) {
        in 1..10 -> println("x is in range of 1 to 10")
        in numbersList -> print("x in numbersList range")
        else -> print("X is not in the range and its value of x is $x")
    }

}

输出:

x in numbersList range


或者范围表达式取非

fun main(args: Array<String>) {
    val x = 15
    when (x) {
        !in 10..20 -> print("x is outside the range")
        else -> print("none of the above")
    }
}

输出:

none of the above


4. when 表达式嵌套语句示例

如符合条件就打印输出,同时返回数值

fun main(args: Array<String>) {
    val x = 10
    val y = 7
    val z = 20
    val result = when (z) {
        20 -> {
            println("if z id 20 then doing the sum of x and y")
            x + y
        }
        30 -> {
            println("if z id 30 then subtracting y from x")
            x - y
        }
        else -> "none of the value matched"
    }
    println("The result is $result")
}

输出:

if z id 20 then doing the sum of x and y
The result is 17


5. when 表达式还可以判断字符串

fun main(args: Array<String>) {
    val namesList= listOf("Waheed","Ali","Akhtar")
    val  name="Waheed"
    when (name) {
        in namesList-> print("User $name exists in our database")
        else -> "name $name does not exit"
    }
}

输出:

User Waheed exists in our database

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值