kotlin
  1. kotlin-integer-type-range

Kotlin Integer Type Range

In Kotlin, the Int type represents integer values ranging from -2,147,483,648 to +2,147,483,647. Kotlin also provides several range operators to check if an integer falls within a certain range. In this tutorial, we'll explore the IntRange class for checking integer type ranges.

Syntax

The basic syntax for creating an IntRange object in Kotlin is as follows:

val range = start..end

start represents the start value of the range, and end represents the end value of the range.

You can also use the in operator to check if an integer falls within the range. The syntax for this is as follows:

val boolInRange = number in range

number represents the integer to be checked for inclusion in the range, and boolInRange represents a Boolean value indicating whether number is within the range or not.

Example

fun main() {
    val range = 1..10
    val number = 5
    val boolInRange = number in range
    println(boolInRange)
}

Output

The above code will output true since 5 falls within the range from 1 to 10.

Explanation

The IntRange class in Kotlin represents a sequence of integers from start to end. It includes both start and end in the range.

We can create an instance of this class using the range operator ... We can then use the in operator to check if a given integer falls within the range.

Use

Checking integer type ranges can be useful in a variety of scenarios, such as validating user input or checking if a value falls within a certain range of values.

Important Points

  • The IntRange class includes both the start and end values in the range.
  • The in operator can be used to check if an integer falls within the range.
  • Use .. operator to create a range of integers.

Summary

In this tutorial, we discussed the IntRange class in Kotlin for checking integer type ranges. We covered the syntax, example, output, explanation, use, and important points of the IntRange class. With this knowledge, you can now check integer type ranges in your Kotlin programs.

Published on: