Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating exclusive ranges in kotlin

Tags:

range

kotlin

I am just starting with Kotlin. I want to create range from 1 to n where n is excluded. I found out that Kotlin has ranges and I can use them as follows

1..n

but this is an inclusive range which includes 1 and n. How do I create exclusive ranges.

like image 787
Chetan Kothari Avatar asked Mar 28 '15 16:03

Chetan Kothari


People also ask

Is Kotlin range inclusive?

A Kotlin range is created with the .. operator or with the rangeTo and downTo functions. Kotlin ranges are inclusive by default; that is, 1.. 3 creates a range of 1, 2, 3 values.

How do you create a range in Kotlin?

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 .. .

What is downTo in Kotlin?

Returns a progression from this value down to the specified to value with the step -1. The to value should be less than or equal to this value. If the to value is greater than this value the returned progression is empty.

What is Kotlin range operator?

Kotlin range is defined as an interval from start value to the end value. Range expressions are created with operator (. .) which is complemented by in and !in. The value which is equal or greater than start value and smaller or equal to end value comes inside the definedrange.


2 Answers

You can use the until function in the Kotlin stdlib:

for (i in 1 until 5) {     println(i) } 

Which will print:

1 2 3 4 
like image 97
Nycto Avatar answered Sep 20 '22 20:09

Nycto


Not sure if this is the best way to do it but you can define an Int extension which creates an IntRange from (lower bound +1) to (upper bound - 1).

fun Int.exclusiveRangeTo(other: Int): IntRange = IntRange(this + 1, other - 1) 

And then use it in this way:

for (i in 1 exclusiveRangeTo n) { //... } 

Here you can find more details about how ranges work.

like image 43
rciovati Avatar answered Sep 22 '22 20:09

rciovati