Kotlin from Learning to Android Chapter 4 Control Flow

if expression

In Kotlin, if is an expression statement that can return a value, so there is no ternary operator (condition ? then : else) in Kotlin.

// 传统的 if 用法
var max = a 
if (a < b) max = b

// 传统的 if 和 else 用法 
var max: Int
if (a > b) {
    max = a
} else {
    max = b
}

// 在 Kotlin 中作为表达式的用法
val max = if (a > b) a else b

A branch of an if expression can also be a code block, and its last expression is the return value of the branch code block.

var a = 3
var b = 5
val max = if (a > b) {
    print("Choose a ")
    a
} else {
    print("Choose b ")
    b
}
println(max)        // 5
val min = if (a < b){
    a
    print("Choose a")
} else {
    b
    print("Choose b")
}
println(min)        // kotlin.Unit

Note : If you use if as an expression and not as a conditional statement, then the if expression must have an else branch.

when expression

The when expression replaces the switch operation, and its general form is:

when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> { // 注意这里的 else
        print("x is neither 1 nor 2")
    }
}

when matches each logical branch one by one in order until it matches successfully. when can be used as both an expression and a conditional statement. When when is used as an expression, the value of the successfully matched branch is the value of the entire when expression; when when is used as a conditional statement, the value of the branch will be ignored automatically. (Like if, the branch of when can also be a code block, and its last expression is the return value of this branch code block.)

When the conditions of all branches are not met, when will match the else branch. If when is used as an expression, it must contain an else branch, unless the compiler can verify that other branches can completely cover all possible matching conditions, that is, one branch must be successfully matched except the else branch, and the else branch can be omitted at this time In fact, the compiler will not verify, for example, the following code still fails to compile in intellij, although it is sure that the else branch will not be taken, but there must be an else.

val a = 1
var b: Int
b = when (a) {
    0 -> 0
    1 -> 1
    2 -> 2
    3 -> 3
    // else -> 3000
}
println(b)

If many conditions are handled in the same way, then these conditions can be written together and separated by commas:

when (x) {
    0, 1 -> print("x == 0 or x == 1")
    else -> print("otherwise")
}

Not only constants can be used as branch conditions, expressions can also be used as branch conditions:

when (x) {
    parseInt(s) -> print("s encodes x")
    else -> print("s does not encode x")
}

Branch conditions can also be modified with in or collections:

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")
}

Of course, you can also use is modification, and you can use the conditionally judged type method without mandatory transformation in the successfully matched branch.

fun hasPrefix(x: Any) = when(x) {
    is String -> x.startsWith("prefix") // 验证通过则说明 x 是 String 类型,不需要再强制转型就可以使用 String 的方法
    else -> false
}

In addition, when can also replace the if-else if relationship chain. If no judgment parameter is passed in, the branch condition is only of Boolean type. When the condition is true, the code block of this branch will be executed.

when {
    x.isOdd() -> print("x is odd")
    x.isEven() -> print("x is even")
    else -> print("x is funny")
}

for loop

The usual way of for loop:

for (item in collection) print(item)

or

for (item: Int in ints) {
    // ...
}

In the for loop, the system will automatically create an iterator, which provides the following methods:

  • iterator()
  • next()
  • hasNext(), returns a Boolean value

If the for loop is created by subscript, then the system will not create iterator, so the performance is relatively high.

for (i in array.indices) {
    print(array[i])
}

Of course, you can also write:

for ((index, value) in array.withIndex()) {
    println("the element at $index is $value")
}

while loop

while and do..while are used in the same way as normal.

while (x > 0) {
    x--
}

do {
    val y = retrieveData()
} while (y != null) 

Guess you like

Origin blog.csdn.net/niuzhucedenglu/article/details/72835749