在Kotlin 中 if是个表达式 ,它会返回一个值,能够替换三元运算符(?:)html
//表达式
val a = if (b > c) b else c
val a = if (b > c) {
a
}else {
b
}
复制代码
when 相似 其余语言的switch. when 将它的参数与全部的分支条件顺序比较,直到某个分支知足条件bash
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 循环能够对任何提供迭代器(iterator)的对象进行遍历函数
集合框架包括Iterable、Iterator 和 Collectionui
- size()、isEmpty()、contains()、constainsAll():集合属性和元素查询是都有的;
- iterator():都有迭代器;
- add()、addAll():添加元素,可变集合才能添加;
- remove()、removeAll():删除元素,可变集合才能删除;
- 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(x > 0) {
x--
}
do {
//
}whle(x > 0)
复制代码
return。默认从最直接包围它的函数或者匿名函数返回。spa
break。终止最直接包围它的循环。.net
continue。继续下一次最直接包围它的循环。code
for(i in 0..10) {
if i == 2 {
break
//return
//continue
}
}
复制代码
在 Kotlin 中任何表达式均可以用标签来标记,标签的格式为标识符后跟
@
符号htm
aaa@ for (i in 0..20) {
for (j in 0...300) {
if j = 100 {
break@aaa
}
}
}
复制代码