Javatpoint Logo
Javatpoint Logo

Kotlin Utility Functions

Kotlin range utility functions have several standard library functions which are used in Kotlin ranges. These utility functions are as follow:

  • rangeTo()
  • downTo()
  • reversed()
  • step()

Kotlin rangeTo()

The rangeTo() function is used to return the value from start to end in increasing order mentioned in a range. The rangeTo() function is integral types which calls the constructors of Range class.

Example of rangeTo() function

Output:

Printing value: 1.rangeTo(5)
1 2 3 4 5 
Printing value: IntRange(1,5)
1 2 3 4 5

The data types (or types) which are floating point like Double, Float are not define in rangeTo operator.

Kotlin downTo()

The downTo() extension function is used to return the value in decreasing order mention from higher order to lower order. The downTo() function is defined for pair of integral types.

Syntax:

Example of downTo() function

Output:

Range 1
5 4 3 2 1 
Range 2
5 4 3 2 1 
Range 3
5 4 3 2 1

Kotlin reversed()

The reversed() function is used to return the reversed order of the given range type.

Syntax:

Example of reversed() function

Output:

Reversed 1
5 4 3 2 1 
Reversed 2
5 4 3 2 1 
Reversed 3
1 2 3 4 5 
Reversed 4
1 3 5

Kotlin step()

The step() function ( or step operator) is used to return the range value in interval of given step value. A step value always takes a positive parameter. The negative step value generates the IllegalArgumentException exception.

Example of step() function

Output:

Print range value with step 2:
1 3 5 7 9 
Print range value with step 3:
1 4 7 10 
First value of interval: 1
Last value of interval: 9

If we provide step value as a negative integer it throws an exception.

Output:

Exception in thread "main" java.lang.IllegalArgumentException: Step must be positive, was: -2.
	at kotlin.ranges.RangesKt__RangesKt.checkStepIsPositive(Ranges.kt:130)
	at kotlin.ranges.RangesKt___RangesKt.step(_Ranges.kt:432)
	at TestKt.main(Test.kt:63)





Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA