Full width home advertisement

Post Page Advertisement [Top]

Kotlin made for loop very easy in compare to any language🔥.

In java we know two types of for loop:
1. Index for loop

2. Iteration for loop
for(Object obj: objectList){

In kotlin we have multiple types of for loop for every moment 😍

Choose your loop according to your mood 😎

1. If we want to start loop with index 1 and upto n, we can use:
//Taking n=10

    print(it) //Every time it contains update index.

2.  If we want to loop between ranges i.e. 10 to 100 (both inclusive)

for(i in 10..100){
    print(i) //No need to create variable i.

3. If we want to loop through 0 to array length - 1

for(i in 0 until array.size){

4. If we want to loop through 100 to 1

for(i in 100 downTo 1){

5.  If we want to loop with steps i.e.  1,3,5,7 and so on...

for(i in 1..100 step 2){

6. If we want step with reverse loop

for(i in 100 downTo 1 step 2){

7. For Each loop in Kotlin.
You dont need to declare a variable to get value from array inside it. Kotlin will auto create.

val someArray = arrayOf(1,2,3,4,5);

for(num in someArray){

Alternatively, you can use powerful kotlin extension lamda function:





someArray.forEachIndexed{i, num->
    print("$num is at index $i")

If we aren't sure that array may be null or not then we use:

someArray?.forEach{ print(it) }

That's all for now. If anyone know more than this let me know that intelligent person 😂.

Kotlin is just "easy". Coding like playing games 😎😋🍃

No comments:

Post a Comment

Bottom Ad [Post Page]

| Designed by Colorlib