Kotlin 控制流 (if ,when ,for, while)

533 阅读2分钟

在Kotlin 控制流 (if ,when ,for, while)

If 表达式

在Kotlin 中 if是个表达式 ,它会返回一个值,可以替换三元运算符(?:)

//表达式
val a = if (b > c) b else c  

val a = if (b > c) {
	   a
}else {
	   b
}

when表达式

when 类似 其他语言的switch. when 将它的参数与所有的分支条件顺序比较,直到某个分支满足条件

when 也可以用来取代 if-else if

// 表达式 块
when(a) {
	 0 -> {
	   //
	 }
	 1 -> {
	   //
	 }
	 else -> {
	 	  //
	 }
}
// 简单表达式
when(a) {
   0 -> print(0)
   1 -> print(1)
   else -> {
   	  print("else")
   }
}
// 并 表达式
when(a) {
  0,1 -> print("0 || 1")
  else -> print("else")
}

// 表达式 函数表达式
fun show(a: Int) : Int {
     return  a * a
}
when (a) {
   show(a) -> print("a")
   else -> print("else")
}
// 区间 in
when(x) {
  in 1..3  -> print("1..3")
  !in 4..5 -> print("not in 4 - 5")
  else -> print("else")
}
// is
when(x) {
  is String -> print("x is String")
  is Int -> print(x is String)
  else -> print("else")
}

For 循环

for 循环可以对任何提供迭代器(iterator)的对象进行遍历

集合框架包括Iterable、Iterator 和 Collection

  1. size()、isEmpty()、contains()、constainsAll():集合属性和元素查询是都有的;
  2. iterator():都有迭代器;
  3. add()、addAll():添加元素,可变集合才能添加;
  4. remove()、removeAll():删除元素,可变集合才能删除;
  5. retainAll()、clear():同样涉及到对元素的删除,可变集合才有的功能。
// 表达式
for(i in 1..3) {
	 println(i)
}

for(i in 9 step 2) {
	print(i)
}

// indices 函数
for (i in array.indices) {
   println(array[i])
}
//withIndex 函数
for ((index, value) in array.withIndex()) {
    println("the element at $index is $value")
}

while 循环

while(x > 0) {
	x--
}

do {
 //
}whle(x > 0)

返回和跳转

return。默认从最直接包围它的函数或者匿名函数返回。

break。终止最直接包围它的循环。

continue。继续下一次最直接包围它的循环。

for(i in 0..10) {
	if i == 2 {
			break
			//return
			//continue
	}
}

标签

在 Kotlin 中任何表达式都可以用标签来标记,标签的格式为标识符后跟 @ 符号

aaa@ for (i in 0..20) {
		for (j in 0...300) {
		    if j = 100 {
		    		break@aaa
		    }
		}
}