Kotlin Reference (四) control flow

KotLin 相关文档


官方在线Reference
kotlin-docs.pdf
Kotlin for android Developers 中文翻译
Kotlin开发工具集成,相关平台支持指南
Kotlin开源项目与Libraries
Kotlin开源项目、资源、书籍及课程搜索平台
Google’s sample projects written in Kotlin
Kotlin and Android

 

If Expression


package com.stone.basic.controlflow

/**
 * desc  :
 * author: stone
 * email : aa86799@163.com
 * time  : 31/05/2017 10 19
 */
object IfExpression {
    @JvmStatic fun main(args: Array<String>) {
        val a = 3; val b = 6
        // Traditional usage
        var max = a
        if (a < b) max = b

        //with else
        if (a > b) {
            max = a
        } else {
            max = b
        }

        if (a > b) {
            max = a
        } else if (a < b) {
            max = b
        }

        if (a > b) {
            max = a
        } else if (a < b) {
            max = b
        } else {
            max = a
        }

        // As expression
        max = if (a > b) a else b

        //作为表达式,并使用语句块。最后一行表达式 表示值
        max = if (a > b) {
            print("Choose a")
            a
        } else {
            print("Choose b")
            b
        }


    }
}

 

When Expression


package com.stone.basic.controlflow


/**
 * desc  :
 * author: stone
 * email : aa86799@163.com
 * time  : 31/05/2017 10 30
 */

//函数表达式中使用 when表达式
fun hasPrefix(x: Any) = when(x) {
    is String -> x.startsWith("prefix") else -> false
}


fun main(args: Array<String>) {
    var x = 10

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

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

    //case 部分 可以作用 任意表达式
    var s = "9527"
    when (x) {
        Integer.parseInt(s) -> print("s encodes x") else -> print("s does not encode x")
    }

    //case 中 使用 范围类型 IntRange
    val validNumbers = IntRange(11, 15)
    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")
    }

    //case中使用表达式,可以替换 if表达式
    val y = IntNumber(112)
    when {
        y.isOdd() -> print("x is odd")
        y.isEven() -> print("x is even")
        else -> print("x is funny")
    }
}

class IntNumber {
    private val num:Int

    constructor(num: Int) {
        this.num = num
    }

    fun isOdd(): Boolean {
        return num % 2 == 1
    }

    fun isEven(): Boolean {
        return num % 2 == 0
    }
}

 

For Loops


package com.stone.basic.controlflow

/**
 * desc  :
 * author: stone
 * email : aa86799@163.com
 * time  : 31/05/2017 11 12
 */
fun main(args: Array<String>) {

    for (item in listOf<Int>()) print(item) //in Collection

    for (item: Float in arrayOf<Float>()) { //in Array , item带上类型
    }

    /*
    使用for 迭代的对象, 都需要通过一个 iterator. 其内部:
    有一个成员或扩展函数,名为iterator(): X ;  且其返回类型中
        有一个成员或扩展函数 next(): T
        有一个成员或扩展函数 hasNext(): Boolean
     */

    var list = listOf<Int>(1, 2)
    for (i in list.indices) {
    }
    var ary = arrayOf(3, 4)
    for (i in ary.indices) {
    }

    for ((index, value) in ary.withIndex()) {//winIndex 返回 Iterable<IndexedValue<T>>
        println("the element at $index is $value")
    }
}

 

While Loops


/**
 * desc  :
 * author: stone
 * email : aa86799@163.com
 * time  : 31/05/2017 13 48
 */

fun main(args: Array<String>) {
    /*
    while and do..while work as usual
     */

    var x = 10
    while (x > 0) {
        x--
    }

    do {
        x++
        val y = x
    } while (y < 10)
}

 

break、continue、return


break、continue、return的一般用法与java中类似。

下面的代码中,还示例了:

使用形如 label@ … break@label 这样的标签式跳转

package com.stone.basic.controlflow


/**
 * desc  :
 * author: stone
 * email : aa86799@163.com
 * time  : 31/05/2017 13 58
 */

fun breakContinueReturn() {
    var x = 10
    while (x > 0) {
        x--
        if (x == 2) {
            break
        }
    }

    do {
        x++
        val y = x
        if (y == 4) {
            continue
        }
        if (y == 5) {
            println(y)
            return
        }
    } while (y < 10)

    println("do sth.")
}

//使用标签 label@ 限制 break或continue、return的跳转
fun labelJump() {
    loop@ for (i in 1..3) {
        inner@ for (j in 1..3) {
            if (i == 1 && j == 3) {
                continue@inner
            }
            if (i == 2 && j == 2) {
                break@loop
            }
            println("$i, $j")
        }
    }
    (1..3).forEach jump@ { item ->
        run {
            if (item == 1) {
                return@jump
            }
            println("-" + item)
        }
    }

    (1..3).forEach { item ->
        run {
            if (item == 1) {
                return@forEach //lambda函数 的标签名与 函数名一致  可以不用像上面那样自定义
            }
            println("-" + item)
        }
    }

    var x = 3
    aa@ for (i in 1..x) {
        b@ for (j in 1..4) {
            if (i == 2 && j == 1) {
                break@aa
            }
        }
    }
}

//使用 匿名函数替换lambda表达式,且使用return后,return的只是该匿名函数
fun anonymousFun() {
    var list = listOf<Int>(3, 4, 5)

    list.forEach(
            fun(value: Int) {
                if (value == 5) return
                println(value)
            }
    )
}

fun main(args: Array<String>) {

    labelJump()

    anonymousFun()
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值