Short step, no thousands of miles; Without small streams, there is no way to become rivers and oceans — “Exhortation to Learn”
Control statements in Kotlin differ from Java in many ways, such as when statements, ternary operators, etc.
directory
The if statement
The if statement in Kotlin is somewhat different from Java in that it can be more flexible in Java, implementing expressions (ternary operators) and using them as a block in addition to Java writing.
1.1. Traditional writing (the sameJava
The same way)
Ex. :
var numA = 2
if (numA == 2) {
println("numA == $numA => true")
}else{
println("numA == $numA => false")
}
Copy the code
The output is:
numA= =2= >true
Copy the code
1.2,Kotlin
The ternary operator in
- There are no ternary operators in Kotlin (
condition ? then : else
) this kind of operation.- That’s because of the nature of the if statement (
if
The expression returns a value), so no ternary operators are needed.
Ex. :
// In Java, you can write this, but Kotlin will directly report an error.
// var numB: Int = (numA > 2) ? 3:5
// Kotlin uses if.. The else instead. Ex. :
var numB: Int = if ( numA > 2 ) 3 else 5 NumB is set to 3 if numA is greater than 2; numB is set to 5 otherwise
println("numB = > $numB")
Copy the code
The output is:
numB = > 3
Copy the code
As you can see above, if in Kotlin can be used as an expression and return a value.
As a block structure, and the last expression is the value of the block
Ex. :
var numA: Int = 2
var numC: Int = if (numA > 2) {
numA++
numA = 10
println("numA > 2 => true")
numA
}else if (numA == 2) {
numA++
numA = 20
println("numA == 2 => true")
numA
}else{
numA++
numA = 30
println("numA < 2 => true")
numA
}
// Each if branch is a block of code that returns a value. The value of numC should be 20 depending on the condition
println("numC => $numC")
Copy the code
The output is:
numA == 2= >true
numC => 20
Copy the code
The for statement
Kotlin
The abolition of theJava
In thefor
(Initial value; Conditions; Increase or decrease step size). butKotlin
For in thefor
The loop statement adds additional rules to satisfy the rules just mentioned.for
Loops provide iterators to iterate over anythingfor
The loop array is compiled as an index-based loop that does not create an iterator object
2.1. New rules should be metfor
(Initial value; Conditions; Increase or decrease step size)
I have something to say about the for loop!
2.1.1, incremental
Keyword: until Range: until[N,m) => That is, the value is greater than or equal to N and less than m
Ex. :
// Loop 5 times, incrementing by 1
for (i in 0 until 5){
print("i => $i \t")
}
Copy the code
The output is
i => 0 i => 1 i => 2 i => 3 i => 4
Copy the code
2.1.2, decreasing
- Key words:
downTo
- Scope:
downTo[n,m]
= > theLess than or equal to n, greater than or equal to m,n >; m
Ex. :
// Loop 5 times and decrement step 1
for (i in 15 downTo 11){
print("i => $i \t")
}
Copy the code
The output is:
i => 15 i => 14 i => 13 i => 12 i => 11
Copy the code
2.1.3 Symbols ('.. '
) represents another operation of an incrementing loop
- Use symbols (
'.. '
).- Scope:
..[n,m]
= > theGreater than or equal to n, less than or equal to m
- and
until
One is simplicity. The second is the difference in scope.
Ex. :
print("Use the symbol '.. 'print result \n")
for (i in 20 .. 25){
print("i => $i \t")
}
println()
print("Use until print \n")
for (i in 20 until 25){
print("i => $i \t")
}
Copy the code
The output is:
Use the symbol '.. 'to print the result
i => 20 i => 21 i => 22 i => 23 i => 24 i => 25
Use the print result from until
i => 20 i => 21 i => 22 i => 23 i => 24
Copy the code
2.1.4. Set the step size
Key words: step
Ex. :
for (i in 10 until 16 step 2){
print("i => $i \t")
}
Copy the code
The output is:
i => 10 i => 12 i => 14
Copy the code
2, iterations,
for
Loops provide an iterator to iterate over anything.for
The loop array is compiled as an index-based loop that does not create an iterator object
2.2. Iterate over the string
Ex. :
for (i in "abcdefg") {
print("i => $i \t")
}
Copy the code
The output is:
i => a i => b i => c i => d i => e i => f i => g
Copy the code
2.3 Go through the number group
Ex. :
Var arrayListOne = arrayOf,20,30,40,50 (10)
for (i in arrayListOne){
print("i => $i \t")
}
Copy the code
The output is:
i => 10 i => 20 i => 30 i => 40 i => 50
Copy the code
2.4. Use arraysindices
Attribute traversal
Ex. :
var arrayListTwo = arrayOf(1.3.5.7.9)
for (i in arrayListTwo.indices){
println("arrayListTwo[$i] => " + arrayListTwo[i])
}
Copy the code
The output is:
arrayListTwo[0] = >1
arrayListTwo[1] = >3
arrayListTwo[2] = >5
arrayListTwo[3] = >7
arrayListTwo[4] = >9
Copy the code
2.5. Use arrayswithIndex()
Methods through
Ex. :
var arrayListTwo = arrayOf(1.3.5.7.9)
for ((index,value) in arrayListTwo.withIndex()){
println("index => $index \t value => $value")
}
Copy the code
The output is:
index => 0 value => 1
index => 1 value => 3
index => 2 value => 5
index => 3 value => 7
index => 4 value => 9
Copy the code
2.7 Iterator traversal
It is usually used with the while loop
Ex. :
var arrayListThree = arrayOf(2.'a'.3.false.9)
var iterator: Iterator<Any> = arrayListThree.iterator()
while (iterator.hasNext()){
println(iterator.next())
}
Copy the code
The output is:
2
a
3
false
9
Copy the code
2.8 foreach traversal
Ex. :
val array = arrayOf(2.'a'.3.false.9)
array.forEach { println(it) }
Copy the code
The output is:
2
a
3
false
9
Copy the code
The when statement
- in
Kotlin
Chinese has been abolishedJava
In theswitch
Statements. And a newwhen(exp){}
Statements.when
Statements can not only be replacedswitch
Statement, and more thanswitch
More powerful statements
3.1. When statement realizes the function of switch statement
Ex. :
when(5) {
1 -> println("1")
2 -> println("2")
3 -> println("3")
5 -> println("5")
else- > {
println("error!")
println("0")
}
}
Copy the code
The output is:
5
Copy the code
3.2 when used together with a comma, it is equivalent to not using the break jump statement in the switch statement
Ex. :
when(1) {
// if x = 1,2, and 3, output 1.
1 , 2 , 3 -> println("1")
5 -> println("5")
else- > {
println("error!")
println("0")
}
}
Copy the code
The output is:
1
Copy the code
3.3. Conditions can use any expression, not just constants
Equivalent to the use of an if expression.
Ex. :
var num:Int = 5
when(num > 5) {
true -> println("num > 5")
false -> println("num < 5")
else- > {
println("error!")
println("num = 5")
}
}
Copy the code
The output is:
num < 5
Copy the code
3.4. Check whether the value exists in a collection or array
(in)
在(! in)
Not in
PS: Applies only to numeric types
Ex. :
var arrayList = arrayOf(1.2.3.4.5)
when(1) {
in arrayList.toIntArray() -> println("1 exists in an arrayList")
in 0.10 -> println("1 belongs to 0 to 10.")
! in5.10 -> println("One does not belong to the five to ten")
else- > {
println("error!")
println("All wrong haha!")
}
}
Copy the code
The output is:
The element1 ` `Exists in an arrayList array
Copy the code
Where, the symbol (..) Indicates the meaning of to. As in the example 0.. 10 means 0 to 10 or 0 to 10.
3.5. Check whether the value is of the specified type
- is
(is)
- not
(! Is)
Ex. :
when("abc") {
is String -> println("ABC is a string")
else- > {
println("ABC is not a string.")
}
}
Copy the code
The output is:
ABC is a string
Copy the code
3.6. When statements that do not use expressions
Is expressed as the simplest Boolean expression
Ex. :
var array = arrayOfNulls<String>(3)
when{
true- > {
for (i in array) {
print(" $i \t")
}
}
else- > {}
}
Copy the code
The output is:
null null null
Copy the code
In summary, this is a common use of the WHEN control statement in Kotlin. You can see how powerful it is. And convenience. Not only can it replace swICTH statements in Java statements. You can even replace the if statement.
While statement
This is the same as the while loop in Java. No elaboration will be made here.
Definition format:
while(expOf) {expFor the expression
.
}
Copy the code
Ex. :
var num = 5
var count = 1
while (num < 10) {
println("num => $num")
println("Loop $count times")
count++
num++
}
Copy the code
The output is:
num= >5
The loop1 次
num= >6
The loop2 次
num= >7
The loop3 次
num= >8
The loop4 次
num= >9
The loop5 次
Copy the code
Fifth, the do… While statement
This is the same as Java do… Same as the while loop. No elaboration will be made here.
Definition format:
do{
.
}while(exp)
Copy the code
Ex. :
var num = 5
var count = 1
do {
println("num => $num")
println("Loop $count times")
count++
num++
}while (num < 10)
Copy the code
The output is:
num= >5
The loop1 次
num= >6
The loop2 次
num= >7
The loop3 次
num= >8
The loop4 次
num= >9
The loop5 次
Copy the code
PS: do{… }while is executed at least once,while(exp) may not be executed at all, as in Java
Ex. :
var num = 5
var count = 1
do {
println("num => $num")
println("Loop $count times")
count++
num++
}while (num < 5)
Copy the code
The output is:
num= >5
The loop1 次
Copy the code
Jump statements (return, break, continue)
1. Return statement
By default, returns from the nearest closed or anonymous function.
Ex. :
fun returnExample(a){
var str: String = ""
if (str.isBlank()){
println("I quit the method.")
return
}
}
Copy the code
2. Break statement
Function: Terminates the most recent closed loop.
Ex. :
var count: Int = 1
for (i in 1 until 10) {
if (i == 5) {
println("I'm the first$iI'm out of the loop.")
break
}
count++
}
println("How many times do I loop: count =>$count")
Copy the code
The output is:
I was in the first5The second time exits the loop
How many times do I loop: count =>5
Copy the code
The continue statement
Progress to the next step (iteration) of the nearest closed loop.
Ex. :
for (i in 1 until 10) {
if (i == 5) {
println("I skipped number one$iLoops")
continue
}
println("i => $i")
}
Copy the code
The output is:
i => 1
i => 2
i => 3
i => 4
I skipped number one5loops
i => 6
i => 7
i => 8
i => 9
Copy the code
Seven,
No matter for any programming language, there are the most basic conditional logic control statements, and their statements are the foundation of learning a programming language. So please be careful and follow the code to type again. Specifically, the for statement and the when statement. Because both of these points change a lot from the Java language. Of course, the ternary operators in the if statement are also worth noting
This article has been collected on GitHub: Jetictors/KotlinLearn, welcome star articles continue to update, can be wechat search “J guy talk” first time read, everyone’s three-in-one is the best power for the old J, you are sure not to wave? If you have any mistakes or suggestions on this blog, please leave comments