Control Flow If expression
In Kotlin, if is an expression that has a return value. But does not support three mesh operations
Val A = 1
val b = 2
var max = a
if (a < b) max = b
var max1:int
if (a > B) {
max1 = a
} else {
max1 = b
}
val max3 = if (a > B) a else B
If the if branch is a block of code, the last expression of the code block defaults to the return value
Val max4 = if (a > B) {
print ("Choose a")
a
} else {
print ("Choose B")
b
}
If an if expression returns a result or if an if expression is assigned as a variable, the ELSE statement block cannot be missing. When expression
Replace a switch statement in Java
When (x) {
1, print ("x = = 1")
2, print ("x = = 2")
else, {//Note
The Block print ("X is Neither 1 nor 2 ")
}
}
When a statement block can also act as an expression or declare a statement, if it is an expression, the branch that meets the criteria is returned as the result of the entire expression. If you are a declarative statement, individual statements are ignored.
The Else branch walks the branch if all conditions are not satisfied. If, as an expression, the Else branch is required.
If there are many branches that return the same results, then you can merge the branches and divide them with numbers:
When (x) {
0, 1--Print ("x = = 0 or x = = 1") Else--
-Print ("otherwise")
}
You can also use any expression as a criterion:
When (x) {
parseint (s), print ("s encodes X")
Else, print ("s does not encode X")
}
You can also use range range as a judging condition to determine whether the passed in value is in a range.
When (x) {in
1..10, print ("x is in the range")
validnumbers--Print ("x is valid")
!in 10..20-> ; Print ("X is outside the range")
else, print ("None of the Above")
}
Of course the IS statement is also supported
Hasprefix (X:any) = when (x) {is
String--X.startswith ("prefix")
else--false
}
If the parameter is not passed in, this branch determines that a condition is true before the branch is left. For Loop
The For loop can traverse any iterator object that contains the iterator () function and does not return an iterative element type
Contains the next () function containing the Hasnext () function, which returns a Boolean value
The above three methods are called operators.
However, if an iterator is not created while the array object is in the For loop, it is traversed based on the index value.
If you want to iterate over the index value, you can use indices to manipulate the array:
Val array = arrayof (2,34,53,435,32) for
(index in array.indices) {
println (index)
}
Withindex getting indexes and values at the same time
For (index, value) in Array.withindex ()) {
println ("The element at $index is $value")
}
While Loop
While statement has 2 formats
While
while (x > 0) {
x--
}
Do While
Do {
val y = retrievedata ()