Article structure:
- Branch statement (if, when)
- Circular statements (for, while)
- Jump statements (break, continue, return, label, throw)
Branch statement (if, when)
if expression
- In kotlin, if is an expression that returns a value
- The if branch can be a code block, and the last expression is the value of the block (the return value of the last line)
fun main(args: Array<String>) { println("hello kotlin !") println(max(2,9)) println(max2(2,9)) println("facts(2) = ${facts(2)}") println("facts(10) = ${facts(10)}") } fun max(x: Int, y: Int): Int { return if (x > y) x else y } fun max2(x: Int, y: Int): Int { val max = if (x>y) { println("max is x") x // The last expression is the value of the block } else { println("max is y") y // The last expression is the value of the block } return max } /** * Factorial function */ fun facts(n: Int): Int { return if (n <= 1) 1 else n * facts(n - 1) }
- There is no Java like ternary expression true in kotlin? 1: 0. The corresponding writing method is if...else statement
The parentheses after if cannot be omitted, and the expression value in parentheses must be Boolean.
when expression
when The expression is similar to switch...case expression;
when All branches are checked until one condition is met
fun main(args: Array<String>) { whenFx(3) whenFx('U') whenFx("hello") whenFx("world") whenFy(3) whenFy(10) whenFy(23) whenFy(30) whenFy(60) whenFy(-1) println("${fact(2)}") println("${fact(10)}") } fun whenFx(x: Any?): Unit { when(x) { // If many branches need the same processing method, you can put multiple branch conditions together and separate them with commas: 0,1,2,3,4,5 -> println("$x Is a 0~5 Integer between") is Char -> println("$x It's a Char Type of data") "hello" -> println("$x Is a string hello") else -> println("[$x] else be similar to java switch...case Medium default.") } } /** * Detect whether a value is in an interval / set */ fun whenFy(x: Int): Unit { val validNum = arrayOf(1,2,3) when(x) { in validNum -> println("$x In collection(1,2,3)in") in 1..10 -> println("$x In range 1..10 in") !in 10..30 -> println("$x Out of range 10..30 in") else -> println("$x , default..") } } /** * Factorial function */ fun fact(n: Int): Int { var data = -1; data = when(n) { 0,1 -> 1 else -> n* fact(n-1) } return data; }
Circular statements (for, while)
for loop
The for loop can traverse any object that provides an iterator.
iterator
fun main(args: Array<String>) { forInArray() forInRange() } fun forInArray(): Unit { val arr = arrayOf(1,2,4,8,16) // for in loop for (x in arr) { println(x) } for (i in arr.indices) { // arr.indices holds a list of subscripts to the array println("$i , ${arr[i]}") } for ( (index,value) in arr.withIndex() ) { // The arr.withIndex() function holds a (subscript, value) list of arrays println("$index : $value") } } /** * Use a for loop in a range expression */ fun forInRange(): Unit { for (i in 10..20) { println(i) } // Equivalent to (10..20).forEach { x -> println("item: $x") } }
while Loop
while and The use method of do...while loop statement is basically the same as that of C and Java languages.
fun main(args: Array<String>) { println("while: ") whileF() println("\ndo...while: ") doWhileF() } fun whileF(): Unit { var x = 10 while (x>5) { x-- print("$x ") } } fun doWhileF(): Unit { var y = 10 do { y++ print("$y ") } while (y<1) }
Jump statements (break, continue, label, return, throw)
break,continue
break,continue Statements are used to control the loop structure and to stop the loop / interrupt jump.
- break Statement is used to completely end a loop and directly jump out of the loop body;
- continue Statement is used to terminate this cycle, but will continue to the next cycle;
return statement
- All functions that have a return value require an explicit return Statement returns its value.
- Function literal: kotlin can directly use the "=" symbol to return the value of a function. Such a function is called 'function literal'.
fun main(args: Array<String>) { val r= sum(1,3) println(r) println(sumF(5,5)) // Output: () - > kotlin.int, the return value of sumF(5,5) is a function, that is () - > kotlin.int println(sumF(5,5).invoke()) // Output: 10. The invoke() function implements the call of sumF function println(sumF(5,5)()) // Output: 10, the () operator is equivalent to the invoke() function println(sumF2(5,15)) // Output: () - > kotlin.int, println(sumF2(5,15).invoke()) // Output: 20 println(sumF2(5,15)()) // Output: 20 } // Declare the sum() function with an expression fun sum(x: Int, y: Int) = x+y // Use the fun keyword to declare an anonymous function, and directly use an expression to implement the function // The type of {x+y} is () - > kotlin.int function; The {x+y} expression returns a Lambda expression // ⚠️ The difference between x+y and {x+y} val sumF = fun(x: Int, y: Int) = { x+y } // The sumF2() function is declared with an expression, {} represents a Lambda expression // ⚠️ The difference between x+y and {x+y} fun sumF2(x: Int, y: Int) = { x + y };
- The difference between the return statement in kotlin and the return statement in lambda expression
- The return statement in kotlin will return from the nearest function (or anonymous function) (similar to the effect of the continue statement in the loop body)
- The return statement in the lambda expression returns directly to the nearest outer function (similar to the break statement effect in the loop body)
fun returnInKotlinVsLambda(): Unit { val arr = intArrayOf(1,2,3,4,5) // Declare an Int array println("return in kotlin function: ") arr.forEach ( fun(x: Int) { // Pass in a function to forEach, and the return statement in this function will not jump out of forEach if (x == 3) return // Similar to the effect of continue statement in the loop body println(x) // Output: 1,2,4,5 } ) println("return in kotlin lambda: ") arr.forEach { // The return statement in a lambda expression returns directly to the nearest outer function if (it == 3) return //Similar to the effect of break statement in loop body println(it) // Output: 1,2 } }
Label label
Use the Label tag to control the jump behavior of return, break and continue statements.
Any expression can be marked with a Label label.
fun labelF(): Unit { val arr = intArrayOf(1,2,3,4,5) // Declare an Int array println("Explicit label:") arr.forEach jump@ { // jump @ is a label if (it == 3) return@jump // The execution jumps to the lambda expression label jump @ and continues the forEach loop println(it) // Output: 1,2,4,5 } println("Implicit label:") arr.forEach { // The implicit tag has the same name as the function that receives the lambda if (it == 3) return@forEach // Return to @ forEach to continue the next cycle println(it) // Output: 1,2,4,5 } }
throw
throw in kotlin is an expression whose type is a special type Nothing.
Nothing type has no value, just like void in C and Java.
fun main(args: Array<String>) { // Use the:: class reference operator to return the type of Nothing // Output: class java.lang.Void println("${Nothing::class}") fail("param type is error !") } fun fail(x: String): Nothing { throw IllegalArgumentException(x) }
Reference for knowledge points: Kotlin from introduction to advanced practice Chen Guangjian