Subscribe for notification
Categories: Android Tutorial

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.

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 –

Sponsored
SyncSaS

SyncSaS Technologies is specialized in creating and designing customized software. We have our own team that will be in charge of developing your softwares.

Share
Published by

Recent Posts

Adsense Updated Dashboard

Changes in Adsense Dashboard Recently you might have seen few changes in Adsense dashboard, these…

4 weeks ago

Guide Book For Google Adsense

With my experience in working as AdSense publisher, I have written many articles, tutorials for…

4 weeks ago

How to manage Google Adsense to get High CPC

Manage Adsense for High CPC CPC (Cost per click) in simple words the CPC is…

4 weeks ago

Google Adsense Introduce page level ads

If you are already the publisher of Google Adsense account then now its time to…

4 weeks ago