20200204[转]Kotlin-When表达式

0 原文

1. When表达式

when 将它的参数和所有的分支条件顺序比较,直到某个分支满足条件。

when 既可以被当做表达式使用也可以被当做语句使用。如果它被当做表达式,符合条件的分支的值就是整个表达式的值,如果当做语句使用, 则忽略个别分支的值。

when 类似其他语言的 switch 操作符。其最简单的形式如下:

fun main(args : Array<String>) {
    for (i in 1..10) {
        println(getType(i))
    }
}

fun getType(x: Int) :String {
    var result : String

    // 类似 Java 的Switch
    when(x) {
        1 -> result = "type 1"
        2 -> result = "type 2"
        3 -> result = "type 3"
        4 -> result = "type 4"
        5, 6 -> result = "type 5, 6"
        in 7..8 -> result = "type 7, 8"
        // 类似 Java 的 Default
        else -> result = ("unknow type, vaule" + x)
    }

    return result
}

运行结果如下:

type 1
type 2
type 3
type 4
type 5, 6
type 5, 6
type 7, 8
type 7, 8
unknow type, vaule9
unknow type, vaule10

Process finished with exit code 0

2 使用 is 智能转换

另一种可能性是检测一个值是(is)或者不是(!is)一个特定类型的值。注意: 由于智能转换,你可以访问该类型的方法和属性而无需 任何额外的检测。

fun main(args : Array<String>) {
    isNumber(123)

    isNumber("hello world")

    isNumber(true)
}

fun isNumber(x : Any) = when (x){
    is Int -> println("is number:" + x)
    is String -> println("is not number, is String :" + x)
    else -> println("is not number, is unknow :" + x)
}

运行结果

is number:123
is not number, is String :hello world
is not number, is unknow :true

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值