IntRange Example in Kotlin
You can define an IntRange object in Kotlin using ..
operator as shown in the following.
x..y
where x and y are integer values.
Or, you can use IntRange constructor as shown in the following.
IntRange(x, y)
where x and y are integer values.
The definition of IntRange constructor is as given below.
IntRange(start: Int, endInclusive: Int)
Create IntRange with start=4 and endInclusive=9
In the following program, we create an IntRange object using its constructor, with a start value of 4, and endInclusive value of 9.
Kotlin Program
fun main() {
val myRange = IntRange(4, 9)
for (i in myRange) {
println(i)
}
}
Output
4
5
6
7
8
9
Create IntRange with start=4 and endInclusive=9, using .. operator
As we have already mentioned, we can create an IntRange object using ..
operator. In the following program, we create an IntRange object with a range of [4, 9],
Kotlin Program
fun main() {
val myRange = 4..9
for (i in myRange) {
println(i)
}
}
Output
4
5
6
7
8
9
Check if element 7 is in the given IntRange
In the following program, we check if the element 7 is present in the IntRange(4, 9).
Kotlin Program
fun main() {
val myRange = IntRange(4, 9)
val element = 7
if (myRange.contains(element)) {
println("$element is present in the given IntRange.")
} else {
println("$element is not present in the given IntRange.")
}
}
Output
7 is present in the given IntRange.