Kotlin Ranges 🎯

beginner
7 min

Kotlin Ranges 🎯

Welcome to the Kotlin Ranges Tutorial! Today, we're going to learn how to work with ranges in Kotlin. This knowledge is essential for handling arrays, lists, and sequences, which are common in many programming tasks. Let's dive in! 🐳

What are Ranges in Kotlin? 📝

A range in Kotlin is a sequence of numbers or characters between a start and end point. It's a useful concept to iterate over a set of values and perform operations on them.

How to Create Ranges 💡

There are two ways to create ranges in Kotlin:

  1. Using .. operator for numerical ranges.
  2. Using downTo and reverse() for descending numerical ranges.
  3. Using .. operator for character ranges.

Numerical Ranges 📝

Forward Ranges 💡

Let's create a simple numerical range from 1 to 10 using the .. operator.

kotlin
fun main() { val numbers = 1..10 println(numbers.toList()) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] }

Descending Ranges 💡

To create a descending range, use the downTo function with reverse() to reverse the sequence.

kotlin
fun main() { val numbers = 10 downTo 1 println(numbers.toList()) // [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] }

Character Ranges 💡

Similar to numerical ranges, character ranges use the .. operator.

kotlin
fun main() { val chars = 'a'..'z' println(chars.toList()) // [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z] }

Using Ranges 💡

Ranges can be used to iterate over a sequence, perform calculations, and more.

Iterating Over a Range 💡

You can iterate over a range using a for-loop. Here's an example of printing numbers from 1 to 10.

kotlin
fun main() { for (number in 1..10) { println(number) } }

Calculating the Sum of Numbers in a Range 💡

To calculate the sum of numbers in a range, you can use a for-loop and the plusAssign operator.

kotlin
fun main() { var sum = 0 for (number in 1..10) { sum += number } println("Sum of numbers from 1 to 10: $sum") }

Quiz Time 🎯

Quick Quiz
Question 1 of 1

What is the output of the following Kotlin code?

That's it for today! Now you know how to create and use ranges in Kotlin. Practice and experiment with these concepts to build a strong foundation for your Kotlin journey! 🚀

Happy coding! 💻


This lesson covers the basics of Kotlin ranges, providing a solid foundation for beginners and a refresher for intermediates. In the next lesson, we'll explore more advanced topics related to Kotlin programming. Stay tuned! 🎓