
Able to define a Kotlin class, create an object instance from it, and access its properties and methods. In the following example, we will traverse through the "Subject" array and we will print the index along with the value. Another option is to maintain a primitive counter, starting with 0, and increment the counter by 1 with each iteration of the loop. Familiar with basic Kotlin programming concepts from Unit 1 of the Android Basics in Kotlin course: the main () function, functions arguments and return values, variables, data types and operations, as well as control flow statements. forEachIndexed is an inline function which takes an array as an input and its index and values are separately accessible. We can iterate over an array, collection, string, range, or anything which can be. Nstead of using forEach() loop, you can use the forEachIndexed() loop in Kotlin. The for loop is used to iterate over any Kotlin object which can be iterated. In this article, we will see how we can access the index of an array in Kotlin while using forEach loop. If the testExpression2 is evaluated to true, continue is executed which skips all the codes inside while loop after it for that iteration.Sometimes it becomes necessary to access the index of an array. It is almost always used with if.else construct.


The result of the if is either Unit in the case of index 2 0 because the setter for age returns a Unit.

In your case, the return value of the Lambda is the if (as most items are expressions in Kotlin). It then adds the result of the Lambda to the new list. The continue construct skips the current iteration of the enclosing loop, and the control of the program jumps to the end of the loop body. The index operator is less noisy than the get () method and is more convenient: val element countries 2 val element countries.get ( 3) We can retrieve the first and last elements of the list using the first () and last () methods, respectively. The mapIndexed will pass each item, and its index into the Lambda. It is sometimes desirable to skip the current iteration of the loop.
