课程 资料

Tips:Kotlin 中没有 switch-case

kotlin条件控制

1.if 表达式

1.1 带返回值 if 表达式

fun maxOf(a:Int,b:Int):Int{ //比较两个值的大小
    if(a>b){
        return a
    }else{
        return b
    }
}

1.2 if 表达式替代三目运算符

fun maxOf2(a:Int,b:Int):Int{ //maxOf简写版
    return if (a > b) a else b
}

1.3 多级 if 表达式

fun eval(number: Number) {
    if (number is Int) {
        println("this is int number")
    } else if (number is Double) {
        println("this is double number")
    } else if (number is Byte) {
        println("this is byte number")
    } else if (number is Short) {
        println("this is Short number")
    } else {
        throw IllegalArgumentException("invalid argument")
    }
}

2.when 表达式

代替java中的 switch case
when 将它的参数与所有的分支条件顺序比较,直到某个分支满足条件

fun eval2(number: Any):String = when(number){
    1 -> "one"
    "hello" -> "hello word"
    is Int -> "int"
    is Double,Float -> "Double 或 Float" ////多个分支条件放在一起,用逗号分隔
    is String -> {
        println("多行when")
        "String"
    }

    else  -> "invalid number"
}

分支条件可以是if 语句,数据类型,具体值

如果不提供参数即when(){…},所有的分支条件都是简单的布尔表达式

3.when 表达式的功能增强

kotlin1.3版本后 when(value) value可以动态赋值,如方法的返回结果

fun eval3() :String = when (val value = getValue()) {
       //when表达式条件直接是一个表达式,并用value保存了返回值, 实际上相当于把外部那一行缩进来写
        is Int -> "This is Int Type, value is $value".apply(::println)
        is String -> "This is String Type, value is $value".apply(::println)
        is Double -> "This is Double Type, value is $value".apply(::println)
        is Float -> "This is Float Type, value is $value".apply(::println)
        else -> "unknown type".apply(::println)
}

fun getValue(): Any {
    return 100F
}

4. 使用 when 表达式替代if表达式

if 表达式一样,when表达式也是带有返回值的。建议对于多层条件级或嵌套条件控制的使用建议使用when替代if-else

主函数调用

fun main() {
    //1.if
    //1.1带返回值 if 表达式
    println("maxOf ${maxOf(3,1)}")
    //1.3 多级 if 表达式
    println("eval ${eval(1.22)} \n")


    //2.when 表达式   (代替java中的switch case)
    println("eval ${eval2(99f)}")

    //3.when 表达式的功能增强
    eval3()
}
Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐