kotlin series --- 3. Conditions control

if expression

An if statement contains a Boolean expression and one or more statements

// 基础用法
var max = a
if (a<b) max = b

// 加上else
var max: Int
if(a>b){
    max = a
}else{
    max = b
}

// 作为表达式
val max = if(a>b) a else b

when expression

  • Other similar language switch operation, as follows
when(x){
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> {
        print("x不是1,也不是2")
    }
}

when both can be used as an expression can be used as statements use, value branch if it is seen as an expression, in line with the conditions that the entire expression, as if the statement uses the value of the individual branches are ignored.

  • A section detecting a value (in) or not (in!) Or a set of:
when (x) {
    in 1..10 -> print("x is in the range")
    in validNumbers -> print("x is valid")
    !in 10..20 -> print("x is outside the range")
    else -> print("none of the above")
}

Guess you like

Origin www.cnblogs.com/gyyyblog/p/11576863.html