For Loop, For Each Loop & Ranges in Kotlin

In Kotlin, the range is a collection of finite values which is defined by endpoints. The range in Kotlin consists of a start, a stop, and the step. The start and stop are inclusive in the Range and the value of step is by default 1.
The range is used with comparable types.

Note that a for loop always implicitly declares a new read-only variable (in this example, name) – if the outer scope already contains a variable with the same name, it will be shadowed by the unrelated loop variable. For the same reason, the final value of the loop variable is not accessible after the loop.

You can also create a range with the .. operator – but beware that unlike Python’s range(), it includes its endpoint:

There are three ways for creating Range in Kotlin –

Using (..) operator
Using rangeTo() function
Using downTo() function
(..) operator

A range defines a closed interval in the mathematical sense: it is defined by its two endpoint values which are both included in the range. Ranges are defined for comparable types: having an order, you can define whether an arbitrary instance is in the range between two given instances. The main operation on ranges is contains, which is usually used in the form of in and !in operators.

See Also  Kotlin Coding Conventions and Keywords

To create a range for your class, call the rangeTo() function on the range start value and provide the end value as an argument. rangeTo() is often called in its operator form.
It is the simplest way to work with range. It will create a range from the start to end including both the values of start and end. It is the operator form of rangeTo() function. Using (..) operator we can create range for integers as well as characters.
Kotlin program of integer range using (..) operator –

0 0 votes
Article Rating

Related articles

Mobile App Development Services

Mobile App Development - Android mobile application developer -...

15 Upbeat IDE for developing Android App

IDE for developing android Application abbreviated as Integrated development...

How to Enable WhatsApp Payment

WhatsApp Pay has finally been given regulatory approval by...

WhatsApp Payment Launch in Brazil

Facebook's WhatsApp messaging service rolled out a system across...

Case Studies

Compass Music Platform

A clothing brand wanted to launch a new e-commerce website that would allow customers to browse and purchase their products online. We developed a...

NewsWeek Magazine

A clothing brand wanted to launch a new e-commerce website that would allow customers to browse and purchase their products online. We developed a...

Beauty & Makeup Shop

A clothing brand wanted to launch a new e-commerce website that would allow customers to browse and purchase their products online. We developed a...
0
Would love your thoughts, please comment.x
()
x