一.if条件语句
在kotlin中,if语句本身就是表达式,有返回值,kotiln并不像java一样会提高三元操作符(condition?then :else), eg:
fun testIf(){
var a:Int=20
var b=30
var max=if(a<b) a else b
println("max")
var min=if (a<b){
println("Choose a:")
a
}else{
println("choose b:")
b
}
val x=6
val y=10
if (x in 1..9){
println("x in area")
}
}
二.when语句
在kotlin中,when语句类似于C语言的switch操作符,else 同 switch 的 default。如果其他分支都不满足条件将会求值 else 分支,如果很多分支需要用相同的方式处理,则可以把多个分支条件放在一起,用逗号分隔,eg:
fun testWhen(){
var x=1
when(x){
1->{
println("x==1")
}
2->{
println("x==2")
}
else->{
println("x neither 1 nor 2")
}
}
when(x){
in 0..10->{
println("x is in 0..10 area")
}
else->{
println("x is not in 0..10 area")
}
}
val items= setOf("apple","pear","orange")
when{
"cherry" in items->{
println("cherry is in fruits")
}
"apple" in items->{
println("apple is fine too")
}
}
}
三.for循环
在kotlin中,for循环可以直接枚举集合中的元素,也可以按集合索引来枚举元素,for 循环可以对任何提供迭代器(iterator)的对象进行遍历,eg:
for (item in collection) print(item)
for (i in array.indices) {
print(array[i])
}
fun testFor(){
val items= listOf("apple","pear","orange")
for (item in items){
println(item)
}
for (index in items.indices){
println("item at $index is ${items[index]}")
}
for ((index,value) in items.withIndex()){
println("the item at $index is $value")
}
}
四.while,do...while循环
在kotlin中,while循环和java中的while循环是一样的,也分为while和do...while,eg:
while( 布尔表达式 ) {
//循环内容
}
do {
//代码语句
}while(布尔表达式);
fun testWhile(){
//while
var x=6
while (x>0){
println(x--)
}
//do...while
var y=8
do {
println(y--)
}while (y>0)
}
五.返回和跳转
在kotlin中,和java语言类似,有三种结构化跳转方式,分别为:
1.return //认从最直接包围它的函数或者匿名函数返回
2.break //终止最直接包围它的循环
3.continue //继续下一次最直接包围它的循环
fun testJump(){
//continue and break
for (i in 1..12){
if (i==5){
continue // i为5时跳过当前循环,继续下一次循环
}
if (i>8){
break // i为8时跳出循环
}
}
}