- if表达式
if…else语句是最基本的流程控制语句,else是可选的。再Kotlin中if是一个表达式,它会返回一个值,函数:String指定返回类型
private fun max(a: Int, b: Int): Int {
return if (a > b) a else b
}
private fun max(a: Int, b: Int): String {
return if (a > b) { //这里{}是一个代码块
println("a...")
"a" //最后一句作为表达式的值
} else {
println("b...")
"b"
}
}
@JvmStatic
fun main(args: Array<String>) {
max(1,2)//调用max函数
}
Kotlin中没有像java那种 true?1:0这种三木表达式对应的写法是
if(true) 1 else 0
if里面只有一条语句{}可以省略,建议加上{}
- when表达式
when表达式类似于 switch…case 表达式。when语句的功能更强大,灵活。
像if语句一样 when 每一个分支也可以是一块代码块。也可以检测是否在一个区间内,也可以是函数
private fun fact1(n: Any?) {
when (n) {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9 -> println("这是一个 0 - 9 间的数字")
"hello" -> println("这是字符串hello")
else -> println("相当于switch case 中的default")
}
}
private fun testWhen(obj: Any?) {
val array = arrayListOf(30, 40, 50)
when (obj) {
in 1..10 -> println("${obj}在1-10之间")
in array -> {
println("在 array ")
}
!in 11..20 -> println("不在这里")
}
}
private fun fact(n: Int): Int {
var result = 1
when (n) {
0, 1 -> result = 1
else -> result = n * fact(n - 1)
}
return result
}
- for循环
for循环可以对任意提供迭代器(iterator)的对象进行遍历。
private fun testFor() {
val list = ArrayList<Int>()
list.add(1)
list.add(12)
list.add(13)
list.add(155)
list.add(122)
list.add(16)
for (item in list){
println(item)
}
}
private fun testFor() {
val list = arrayOf(1, 2, 3, 4, 5)
for (item in list.indices) {//list.indices 持有数组下标
println(list[item])
}
}
//范围 Ranges也可以用在循环中
private fun testFor() {
for (i in 1..10){
println(i)
}
}
//代码简写如下 相当于 1.rangeTo(10)
(1..10).forEach { println(it) }
//求1!...10!的和
private fun testFor(n: Int): Int {
var sum = 0
for (i in 1..n) {
sum += fact(i)
}
return sum
}
- while循环
while和do…while语句和java语言基本一致
private fun testWhile() {
var x = 10
while (x > 0) {
x--
println(x)
}
}
private fun testWhile() {
var y = 10
do {
y += 1
println(y)
} while (y < 20)
}
-
break 和 continue
break完全结束一个循环,直接跳转到循环出口,continue结束本轮循环继续下轮循环 -
return
private fun testReturn(a: Int, b: Int): Int {
if (a > b) {
return a //此处return不能省略
} else {
return b
}
}
//kotlin中可以使用==符号返回一个函数的值,这样函数的值称为函数字面量
fun sum(a: Int, b: Int) = a + b