关于Android开发的那些事儿kotlinKotlin专题

Kotlin_lesson_02_流程控制

2017-06-19  本文已影响41人  Bear_android

if表达式

// Traditional usage
var max = a
if (a < b) max = b
// With else
var max: Int if (a > b) {
    max = a 
} else {
    max = b
}
// As expression
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的分支。

When表达式

when代替switch结构

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

when接口会顺序匹配他的所有条件分支,并执行所有满足条件的分支。when不但能用于表达式,同时也能表示状态值。如果当作时表达式,满足条件的分支将是整个表达式的值。如果作为状态值,则条件所对应的值不会影响表达式的值,只是满足条件的最后一个分支的值为整个表达式的值。

如果有多个条件需要满足,则只需把多个条件连接写出来用逗号隔开:

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

我们可以用任意的表达式作为条件而不仅仅是常数:

when (x) {
parseInt(s) -> print("s encodes x") 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")
}

另外也可用于判断一些特殊类型:

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

when也可以替换if-else if结构题,当不写参数的时候,每个条件分支为boolean表达式,分支为true的时候执行:

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

for循环

for循环可以迭代任何可以迭代的东西。语法如下:

for (item in collection) print(item)

也可以写为代码块:

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

如前所述,迭代器提供了三个方法:

如下对array进行遍历:

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

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

While循环

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

Break和contunue在循环中的使用

kotlin支持循环体中传统的break和continue操作符

返回和跳过

kotlin又三种跳转结构表达式:

以上操作符可以运用在比较大的表达式中

val s = person.name ?: return

break和continue标签

任何表达式在kotlin中建议使用label。lable接口为lableName@.例如abc@,foobar.标记一个表达式,我们直接将标记放在表达式之前:

loop@ for (i in 1..100) { // ...
}

我们可以使用break或者continue结束某个带标签的表达式

loop@ for (i in 1..100) { 
for (j in 1..100) {
    if (...) break@loop 
    }
}

return某个标签表达式

fun foo() { 
    ints.forEach {
        if (it == 0) return
        print(it) 
    }
}

可以通过增加标签,而结束对应方法

fun foo() { 
    ints.forEach lit@ {
        if (it == 0) return@lit
        print(it) 
    }
}

在lambda表达式重,通常会引用内部方法名为label

fun foo() { 
    ints.forEach {
        if (it == 0) return@forEach
        print(it) 
    }
}

当然,也可以奖lambda表达式替换为匿名方法

fun foo() { 
    ints.forEach(fun(value: Int) {
        if (value == 0) return
        print(value) 
    })
}

当返回一个值时,会返回对应对象的引用值

return@a 1

返回的不是一个表达式,而是 标签为1的值为1.

上一篇下一篇

猜你喜欢

热点阅读