button.setOnClickListener { if (flag) { text.text = "I love you, at the first sight of you." } else { text.text = "I love three things in this world.Sun, moon and you. " + "Sun for morning, moon for night, and you forever." } }
而Kotlin的if else可以有返回值
例子
1 2 3 4 5 6 7 8
button.setOnClickListener { text.text = if (flag) { "I love you, at the first sight of you." } else { "I love three things in this world.Sun, moon and you. " + "Sun for morning, moon for night, and you forever." } }
Kotlin中没有java,C/C++的三目运算符,但是可以用if…else…取代
例子
1 2 3 4 5 6 7
button.setOnClickListener { text.text = if (flag) (16).toString() else (153.6).toString() /* 像极了三目元算符:(假装这里是C/C++或java) text.text = flag ? (16).toString() : (153.6).toString(); */ }
button.setOnClickListener { text.text = when(type) { 1,2,3 -> "I love you, at the first sight of you."//多个值走同一个分支,用逗号隔开 in4..10 -> "I love three things in this world.Sun, moon and you. " + "Sun for morning, moon for night, and you forever."//表示在4到10之间 !in1..10 -> "We don't talk anymore."//表示不在1到10之间 else -> "error" } }
btn.setOnClickListener { var str:String = "0123456789" for (item in str) {//item自动类型推断 Toast.makeText(this, "${item}", Toast.Toast.LENGTH_SHORT).show() } }
例子(下标数组遍历)
1 2 3 4 5 6
btn.setOnClickListener { var str:String = "0123456789" for (i in str.indices) {//indices是下标数组 Toast.makeText(this, "${str[i]}", Toast.Toast.LENGTH_SHORT).show() } }
条件循环
格式
1 2 3 4 5 6
for(i in11 until 66) {} //左闭右开区间,[11,66) for (i in23..89 step 4) {} //每次循环,i += 4,如果条件允许,可以到89 for (i in50 downTo 7) {} //从50 递减到 7
while循环
用法同java/C/C++
do-while循环
用法同java/C/C++
跳出多重循环
和java类似,如果想一次性跳出多个循环,可以在循环外面加”标签”
例子
1 2 3 4 5 6 7 8 9 10 11 12
var i:Int = 0 var j:Int = 0 @outsidewhile (i <= 10) { j = 10; while (i * j != 50) { j-- if (j == 0) { break@outside } } i++ }