Kotlin Ranges
Working with sequences of values
📊 What are Ranges?
Ranges represent sequences of values with a start and end point. They're perfect for loops, checking if values fall within bounds, and creating collections of sequential data efficiently and elegantly in Kotlin.
// Basic range examples
val numbers = 1..10 // 1 to 10 inclusive
val letters = 'a'..'z' // a to z inclusive
val countdown = 10 downTo 1 // 10 to 1 backwards
Types of Ranges
Closed Range
Includes both start and end values
val range = 1..5
// Contains: 1, 2, 3, 4, 5
Open Range
Excludes the end value
val range = 1 until 5
// Contains: 1, 2, 3, 4
Reverse Range
Count backwards
val range = 5 downTo 1
// Contains: 5, 4, 3, 2, 1
Step Range
Skip values with step
val range = 1..10 step 2
// Contains: 1, 3, 5, 7, 9
🔹 Creating Ranges
Different ways to create ranges:
fun main() {
// Closed ranges (inclusive)
val numbers = 1..10
val letters = 'a'..'f'
val floats = 1.0..5.0
println("Closed ranges:")
println("Numbers 1..10: ${numbers.toList()}")
println("Letters 'a'..'f': ${letters.toList()}")
// Open ranges (exclusive end)
val openRange = 1 until 10
println("\nOpen range 1 until 10: ${openRange.toList()}")
// Reverse ranges
val countdown = 10 downTo 1
val reverseLetters = 'z' downTo 'u'
println("\nReverse ranges:")
println("Countdown 10 downTo 1: ${countdown.toList()}")
println("Letters 'z' downTo 'u': ${reverseLetters.toList()}")
// Step ranges
val evens = 0..20 step 2
val odds = 1..20 step 2
println("\nStep ranges:")
println("Even numbers 0..20 step 2: ${evens.toList()}")
println("Odd numbers 1..20 step 2: ${odds.toList()}")
}
Output:
Closed ranges:
Numbers 1..10: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Letters 'a'..'f': [a, b, c, d, e, f]
Open range 1 until 10: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Reverse ranges:
Countdown 10 downTo 1: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Letters 'z' downTo 'u': [z, y, x, w, v, u]
Step ranges:
Even numbers 0..20 step 2: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Odd numbers 1..20 step 2: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
🔹 Using Ranges in Loops
Ranges are perfect for for loops:
fun main() {
// Basic counting
println("Counting 1 to 5:")
for (i in 1..5) {
print("$i ")
}
// Countdown
println("\n\nCountdown from 5:")
for (i in 5 downTo 1) {
print("$i ")
}
println("🚀")
// Skip counting
println("\nEven numbers from 2 to 10:")
for (i in 2..10 step 2) {
print("$i ")
}
// Character ranges
println("\n\nFirst 5 letters:")
for (letter in 'A'..'E') {
print("$letter ")
}
// Practical example: Creating a multiplication table
println("\n\nMultiplication table for 3:")
for (i in 1..10) {
println("3 × $i = ${3 * i}")
}
}
Output:
Counting 1 to 5:
1 2 3 4 5
Countdown from 5:
5 4 3 2 1 🚀
Even numbers from 2 to 10:
2 4 6 8 10
First 5 letters:
A B C D E
Multiplication table for 3:
3 × 1 = 3
3 × 2 = 6
3 × 3 = 9
3 × 4 = 12
3 × 5 = 15
3 × 6 = 18
3 × 7 = 21
3 × 8 = 24
3 × 9 = 27
3 × 10 = 30
🔹 Checking if Values are in Range
Use 'in' operator to check membership:
fun main() {
val validAges = 18..65
val grades = 'A'..'F'
val workingHours = 9..17
// Check ages
val ages = listOf(16, 25, 45, 70, 30)
println("Age validation (valid range: 18-65):")
for (age in ages) {
if (age in validAges) {
println("✅ Age $age: Valid for employment")
} else {
println("❌ Age $age: Outside valid range")
}
}
// Check grades
val studentGrades = listOf('A', 'B', 'X', 'C', 'Z')
println("\nGrade validation (valid grades: A-F):")
for (grade in studentGrades) {
if (grade in grades) {
println("✅ Grade '$grade': Valid")
} else {
println("❌ Grade '$grade': Invalid")
}
}
// Check working hours
val currentHour = 14 // 2 PM
println("\nCurrent time: ${currentHour}:00")
if (currentHour in workingHours) {
println("✅ Office is open!")
} else {
println("❌ Office is closed!")
}
}
Output:
Age validation (valid range: 18-65):
❌ Age 16: Outside valid range
✅ Age 25: Valid for employment
✅ Age 45: Valid for employment
❌ Age 70: Outside valid range
✅ Age 30: Valid for employment
Grade validation (valid grades: A-F):
✅ Grade 'A': Valid
✅ Grade 'B': Valid
❌ Grade 'X': Invalid
✅ Grade 'C': Valid
❌ Grade 'Z': Invalid
Current time: 14:00
✅ Office is open!
🔹 Range Properties and Functions
Useful properties and methods:
fun main() {
val range = 5..15
val stepRange = 1..20 step 3
val charRange = 'a'..'z'
// Basic properties
println("Range properties:")
println("Range: $range")
println("First: ${range.first}")
println("Last: ${range.last}")
println("Step: ${range.step}")
// Check if empty
val emptyRange = 10..5 // Invalid range
println("\nEmpty range check:")
println("Range 10..5 isEmpty: ${emptyRange.isEmpty()}")
println("Range 5..15 isEmpty: ${range.isEmpty()}")
// Convert to list
println("\nConverting to collections:")
println("Range as list: ${range.toList()}")
println("Step range as list: ${stepRange.toList()}")
println("First 5 letters: ${charRange.take(5).toList()}")
// Random from range
println("\nRandom values:")
repeat(5) {
println("Random from 1..100: ${(1..100).random()}")
}
// Contains check
println("\nContains check:")
println("Does 1..10 contain 5? ${5 in 1..10}")
println("Does 1..10 contain 15? ${15 in 1..10}")
}
Output:
Range properties:
Range: 5..15
First: 5
Last: 15
Step: 1
Empty range check:
Range 10..5 isEmpty: true
Range 5..15 isEmpty: false
Converting to collections:
Range as list: [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
Step range as list: [1, 4, 7, 10, 13, 16, 19]
First 5 letters: [a, b, c, d, e]
Random values:
Random from 1..100: 42
Random from 1..100: 73
Random from 1..100: 18
Random from 1..100: 91
Random from 1..100: 56
Contains check:
Does 1..10 contain 5? true
Does 1..10 contain 15? false
🔹 Practical Range Applications
Real-world examples using ranges:
fun main() {
// Password strength checker
fun checkPasswordStrength(password: String): String {
val length = password.length
return when {
length in 1..5 -> "❌ Very Weak (too short)"
length in 6..8 -> "⚠️ Weak"
length in 9..12 -> "✅ Good"
length in 13..20 -> "🔒 Strong"
length > 20 -> "🛡️ Very Strong"
else -> "❌ Invalid"
}
}
// Test passwords
val passwords = listOf("123", "password", "mySecretPass", "superSecurePassword123", "thisIsAnExtremelyLongPasswordThatIsVerySecure")
println("Password Strength Analysis:")
for (password in passwords) {
val strength = checkPasswordStrength(password)
println("'${password.take(10)}${if (password.length > 10) "..." else ""}' (${password.length} chars): $strength")
}
// Grade calculator
fun calculateGrade(score: Int): String {
return when (score) {
in 90..100 -> "A (Excellent)"
in 80..89 -> "B (Good)"
in 70..79 -> "C (Average)"
in 60..69 -> "D (Below Average)"
in 0..59 -> "F (Fail)"
else -> "Invalid Score"
}
}
println("\nGrade Calculator:")
val scores = listOf(95, 87, 76, 65, 45, 105)
for (score in scores) {
println("Score $score: ${calculateGrade(score)}")
}
// Age group classifier
fun getAgeGroup(age: Int): String {
return when (age) {
in 0..2 -> "👶 Toddler"
in 3..12 -> "🧒 Child"
in 13..19 -> "👦 Teenager"
in 20..39 -> "👨 Young Adult"
in 40..59 -> "👨💼 Middle-aged"
in 60..120 -> "👴 Senior"
else -> "❓ Invalid Age"
}
}
println("\nAge Group Classification:")
val ages = listOf(2, 8, 16, 25, 45, 70)
for (age in ages) {
println("Age $age: ${getAgeGroup(age)}")
}
}
Output:
Password Strength Analysis:
'123' (3 chars): ❌ Very Weak (too short)
'password' (8 chars): ⚠️ Weak
'mySecretPa...' (12 chars): ✅ Good
'superSecur...' (23 chars): 🛡️ Very Strong
'thisIsAnEx...' (49 chars): 🛡️ Very Strong
Grade Calculator:
Score 95: A (Excellent)
Score 87: B (Good)
Score 76: C (Average)
Score 65: D (Below Average)
Score 45: F (Fail)
Score 105: Invalid Score
Age Group Classification:
Age 2: 👶 Toddler
Age 8: 🧒 Child
Age 16: 👦 Teenager
Age 25: 👨 Young Adult
Age 45: 👨💼 Middle-aged
Age 70: 👴 Senior