Kotlin-1.3-控制流程(if, when, for, while)

来源:互联网 发布:github源码在微信上 编辑:程序博客网 时间:2024/05/29 14:57

翻译自官方权威文档:Basics-Control Flow
如有错误或者疏漏,欢迎指正!
本文除译文外会增添个人理解的知识点。

  • 1-控制流程 if when for while
    • 1-If 表达式
    • 2-When Expression
    • 3-For循环
    • 4-While循环
    • 5-循环中的Break 和continue
  • 2-Control Flow if when for while
    • 1-If Expression
    • 2-When Expression
    • 3-For Loops
    • 4-While Loops
    • 5-Break and continue in loops

1-控制流程: if, when, for, while

1-If 表达式

在Kotlin中,if是一种表达式,也就是说,它返回一个值。因此没有三元操作符(条件?然后:否则),因为普通的if也能完成该功能。

// 传统使用var max = a if (a < b) max = b// 和else一起var max: Intif (a > b) {    max = a} else {    max = b}// As 表达式val max = if (a > b) a else b

if 分支可以有代码块,最后一个表达式就是代码块的值:

val max = if (a > b) {    print("Choose a")    a} else {    print("Choose b")    b}

如果你正在使用if作为表达式而不是一个语句(例如,返回它的值或者分配给一个变量),该表达式需要有else分支。

See the grammar for if.

2-When Expression

when 代替了类C语言中的switch操作符。简单实例如下:

when (x) {    1 -> print("x == 1")    2 -> print("x == 2")    else -> { // 注意该代码块        print("x is neither 1 nor 2")    }}

when 顺序比对所有分支,直到匹配到符合分支就停止。when 可被用作表达式或者语句。如果被用作表达式,合适分支的值会作为整个表达式的值。如果被用作语句,分支的值会被省略。(就像if一样,每个分支都可以是代码块,该分支的值是代码块中最后一个表达式的值。)

若其他分支都没有符合条件,那么会进入到else分支。当when作为表达式时,else分支是强制的,除非编译器可以证明所有可能的情况都被分支条件囊括了。

如果很多情况需要用相同方法解决,分支条件可以用逗号组合起来:

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

我们可以使用任意表达式作为分支条件(不仅仅是常量):

when (x) {    parseInt(s) -> print("s encodes x") //parseInt(s)将string转为int    else -> print("s does not encode x")}

我们也可以判断一个值是否in 或者 !in 一个范围中 或者集合中:

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

另一种方法是判断数值is或者!is一个特定的类型。注意,由于smart casts,你可以访问该类型的方法或者属性而不需要额外的判断,如下:

fun hasPrefix(x: Any) = when(x) {    is String -> x.startsWith("prefix")//没有额外判断,就可以调用String的方法    else -> false}

when也可以替代if-else if链. 如果没有提供参数,分支条件可以是简单的布尔表达式,当条件满足时,相应分支就可以执行:

when { //没有提供参数    x.isOdd() -> print("x is odd") //直接进行boolean判断    x.isEven() -> print("x is even")    else -> print("x is funny")}

See the grammar for when.

3-For循环

for 循环能迭代所有提供迭代器的对象。这等价于C#语言中的foreach循环。语法如下:

for (item in collection) print(item)

主体可以是代码块:

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

正如上面提到的,for能迭代任何包含迭代器的对象,即:As mentioned before, for iterates through anything that provides an iterator, i.e.

  • 有成员函数or扩展函数iterator,并返回type
  • 有成员函数or扩展函数next()
  • 有成员函数or扩展函数hasNext(),并返回Boolean.

(扩展函数参考:Kotlin-2.5- 扩展)

这些函数都需要使用operator来标记。

for 遍历数组会被编译成依赖index索引的循环,这样可以不创造一个迭代器对象。

如果你想要迭代一个数组或者使用索引的列表,你可以这样做:

for (i in array.indices) { //利用index进行遍历    print(array[i])}

注意,“遍历一个范围”会被编译为没有创建额外对象的一种优化过的实现。

另外,你可以使用withIndex库函数:

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

See the grammar for for.

4-While循环

whiledo..while 工作方式按照惯例:

while (x > 0) {    x--}do {    val y = retrieveData()} while (y != null) // y这里可见!

See the grammar for while.

5-循环中的Break 和continue

Kotlin支持传统的breakcontinue操作符。参考:Kotlin-1.4-跳转和返回.


翻译自官方权威文档:Kotlin-Basics-Control Flow

2-Control Flow: if, when, for, while

1-If Expression

In Kotlin, if is an expression, i.e. it returns a value. Therefore there is no ternary operator (condition ? then : else), because ordinary if works fine in this role.

// Traditional usage var max = a if (a < b) max = b// With else var max: Intif (a > b) {    max = a} else {    max = b}// As expression val max = if (a > b) a else b

if branches can be blocks, and the last expression is the value of a block:

val max = if (a > b) {    print("Choose a")    a} else {    print("Choose b")    b}

If you’re using if as an expression rather than a statement (for example, returning its value or assigning it to a variable), the expression is required to have an else branch.

See the grammar for if.

2-When Expression

when replaces the switch operator of C-like languages. In the simplest form it looks like this

when (x) {    1 -> print("x == 1")    2 -> print("x == 2")    else -> { // Note the block        print("x is neither 1 nor 2")    }}

when matches its argument against all branches sequentially until some branch condition is satisfied. when can be used either as an expression or as a statement. If it is used as an expression, the value of the satisfied branch becomes the value of the overall expression. If it is used as a statement, the values of individual branches are ignored. (Just like with if, each branch can be a block, and its value is the value of the last expression in the block.)

The else branch is evaluated if none of the other branch conditions are satisfied. If when is used as an expression, the else branch is mandatory, unless the compiler can prove that all possible cases are covered with branch conditions.

If many cases should be handled in the same way, the branch conditions may be combined with a comma:

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

We can use arbitrary expressions (not only constants) as branch conditions

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

We can also check a value for being in or !in a range or a collection:

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

Another possibility is to check that a value is or !is of a particular type. Note that, due to smart casts, you can access the methods and properties of the type without any extra checks.

fun hasPrefix(x: Any) = when(x) {    is String -> x.startsWith("prefix")    else -> false}

when can also be used as a replacement for an if-else if chain. If no argument is supplied, the branch conditions are simply boolean expressions, and a branch is executed when its condition is true:

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

See the grammar for when.

3-For Loops

for loop iterates through anything that provides an iterator. This is equivalent to the foreach loop in languages like C#. The syntax is as follows:

for (item in collection) print(item)

The body can be a block.

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

As mentioned before, for iterates through anything that provides an iterator, i.e.

  • has a member- or extension-function iterator(), whose return type
  • has a member- or extension-function next(), and
  • has a member- or extension-function hasNext() that returns Boolean.

All of these three functions need to be marked as operator.

A for loop over an array is compiled to an index-based loop that does not create an iterator object.

If you want to iterate through an array or a list with an index, you can do it this way:

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

Note that this “iteration through a range” is compiled down to optimal implementation with no extra objects created.

Alternatively, you can use the withIndex library function:

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

See the grammar for for.

4-While Loops

while and do..while work as usual

while (x > 0) {    x--}do {    val y = retrieveData()} while (y != null) // y is visible here!

See the grammar for while.

5-Break and continue in loops

Kotlin supports traditional break and continue operators in loops. See Returns and jumps.

阅读全文
0 0