![]() ![]() Let's see the same example once again, but this time we will iterate through the array using its index. Var fruits = arrayOf("Orange", "Apple", "Mango", "Banana") Kotlin Array is another data type which provides iterator, so we can use for loop to iterate through a Kotlin array in the similar way as we did it for the ranges.įollowing is an example where we used for loop to iterate through an array of strings: Let's see one more example where the loop will iterate through another range, but this time it will step down instead of stepping up as in the above example: When you run the above Kotlin program, it will generate the following output: To iterate over a range of numbers, we will use a range expression: We will study Kotlin Ranges in a separate chapter, for now you should know that Kotlin Ranges provide iterator, so we can iterate through a range using for loop.įollowing is an example where the loop iterates through the range and prints individual item. The syntax of the Kotlin for loop is as follows: Kotlin does not provide a conventional for loop which is available in C, C++ and Java etc. In this authoritative guide, you’ll take on the challenge of learning functional programming. Kotlin for loop is equivalent to the foreach loop in languages like C#. Simplicity and modularity (and fewer bugs) Functional Programming in Kotlin is a reworked version of the bestselling Functional Programming in Scala, with all code samples, instructions, and exercises translated into the powerful Kotlin language. that contains a countable number of values, for example arrays, ranges, maps or any other collection available in Kotlin. Kotlin for loop iterates through anything that provides an iterator ie. Kotlin supports various types of loops and in this chapter we are going to learn Kotlin for loop. Actually, Loops are used in programming to repeat a specific block of code until certain condition is met. What about if you need to print the same sentence one thousand times? This is where we need to use loops to simplify the programming job. You can do it by using print statement 20 times. Imagine a situation when you need to print a sentence 20 times on your screen.
0 Comments
Leave a Reply. |