kotlin条件控制

条件控制是每门编程语言中必不可少的,一般就是使用我们所熟知的if-else ,来作为我们代码逻辑选择条件控制。再java中一般使用 if-else 和 switch-case 来作为条件控制,而在kotlin中则是使用 if-else 和when 来控制条件控制

tips: kotlin 中没有 switch-case .

if表达式

带返回值的if表达式

再kotlin 中,if 是一个表达式所以它会返回一个值,表达式的值为表达式作用域内最后一行的值。这一点和java 是不同的,再java中 if 仅仅是语句

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

fun maxOf2(a: Int, b: Int): Int {
    //三目运算
    return if(a > b) a else b
}
fun eval(number: Number){
    //如果是Int类型
    //is 是判断是否是某一种类型
    if (number is Int) {
        println("this is int number")
    } else if (number is Double) {
        println("this is double number")
    } else if(number is Float) {
        println("this is float number")
    } else if (number is Long) {
        println("this is long 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")
    }
}

when表达式

再kotlin中使用 when 表达式代替了类似C语言的swith-case 语句。

//when 同样是带有返回值
//when 将他的参数与所有的分支条件顺序比较,直到某个分支满足条件
fun eval2(number: Number): String = when (number) {
    100 -> "the number is 100"
    200f -> "this number is 200f"

    is Int -> "this is int number"
    is  Double -> "this is double number"
    is Float -> {
//        println("this number is float")
        "this is float number6666"
    }
    is Long -> "this is long number"
    is Byte -> "this is byte number"
    is Short -> "this is Short number"
    else -> "invalid number"
}

when表达式的功能增强

自从kotlin1.3版本后 when 表达式做了一个写法上的优化,为什么这么说呢?再kotlin1.3版本之前 when 表达式内部是不能传入值的

    return when (val value:Any = getValue()) {
        //这个 Lambda 表达式使用了一个单表达式函数,它使用 apply 函数将字符串 this is int type,
        // value is $value 应用到一个可以打印字符串的函数上。
        // apply 函数返回一个带有 println 函数调用的字符串,println 函数将字符串输出到控制台。
        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 {//类似于java中的object
    return 100
}

//条件控制
fun main() {
    println("maxOf:${maxOf(5,10)}")

    eval(100)
    eval2(200f)
    println("111:${eval2(200f) }")
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值