kotlinbeginner
Ranges, Progressions, and Coercion
Use Kotlin ranges: IntRange, custom progressions, coerceIn, and range-based iteration patterns.
kotlinPress ⌘/Ctrl + Shift + C to copy
fun main() {
// Basic ranges
val intRange = 1..10
val charRange = 'a'..'z'
val longRange = 1L..1_000_000L
// Membership
println("5 in 1..10: ${5 in intRange}")
println("'m' in a..z: ${'m' in charRange}")
println("15 in 1..10: ${15 in intRange}")
// until (exclusive end)
val exclusive = 0 until 10 // 0..9
println("\n0 until 10: ${exclusive.toList()}")
// downTo
val countdown = 10 downTo 1
println("10 downTo 1: ${countdown.toList()}")
// Step
val evens = 0..20 step 2
println("Evens: ${evens.toList()}")
val oddCountdown = 9 downTo 1 step 2
println("Odd countdown: ${oddCountdown.toList()}")
// Progression properties
val prog = 1..10 step 3
println("\nProgression: first=${prog.first}, last=${prog.last}, step=${prog.step}")
// Range in when
fun classify(score: Int): String = when (score) {
in 90..100 -> "A"
in 80 until 90 -> "B"
in 70 until 80 -> "C"
in 0 until 70 -> "F"
else -> "Invalid"
}
println("\nScore 85: ${classify(85)}")
println("Score 95: ${classify(95)}")
// Coercion
val value = 150
println("\nCoerce 150 in 0..100: ${value.coerceIn(0..100)}")
println("Coerce -5 at least 0: ${(-5).coerceAtLeast(0)}")
println("Coerce 200 at most 100: ${200.coerceAtMost(100)}")
// Custom range class
data class Version(val major: Int, val minor: Int) : Comparable<Version> {
override fun compareTo(other: Version) = when {
major != other.major -> major - other.major
else -> minor - other.minor
}
override fun toString() = "$major.$minor"
}
val supported = Version(2, 0)..Version(4, 0)
val current = Version(3, 5)
println("\n$current in $supported: ${current in supported}")
// Range-based array slicing
val arr = intArrayOf(10, 20, 30, 40, 50, 60, 70, 80)
val slice = arr.slice(2..5)
println("\nSlice [2..5]: $slice")
// String range
val alpha = "Hello World".slice(0..4)
println("Slice: $alpha")
// Iteration patterns
println("\n--- Iterations ---")
for (i in 1..5) print("$i "); println()
for (i in 5 downTo 1) print("$i "); println()
for (i in 0 until 10 step 3) print("$i "); println()
for (c in 'A'..'F') print("$c "); println()
// repeat
repeat(3) { i -> print("repeat-$i ") }; println()
// Functional with ranges
val squares = (1..5).map { it * it }
println("\nSquares: $squares")
val sum = (1..100).sum()
println("Sum 1..100: $sum")
val filtered = (1..20).filter { it % 3 == 0 || it % 5 == 0 }
println("FizzBuzz: $filtered")
}Use Cases
- Score and category classification
- Value clamping and bounds checking
- Index-based iteration patterns
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
kotlinbeginner
Null Safety — Elvis, Safe Call, and let
Master Kotlin null safety: safe calls, Elvis operator, let/also scoping, and smart casts.
Best for: Safe navigation through nullable chains
#kotlin#null-safety
kotlinbeginner
Data Classes — Copy, Destructure, and Equals
Use data classes for immutable models: auto-generated equals, hashCode, copy, and destructuring.
Best for: Immutable domain models and DTOs
#kotlin#data-class
kotlinbeginner
Scope Functions — let, run, apply, also, with
Master Kotlin scope functions: when to use let, run, apply, also, and with for concise code.
Best for: Object initialization and configuration
#kotlin#scope-functions
kotlinbeginner
Collections — map, filter, groupBy, and More
Master Kotlin collections: functional transformations, aggregations, grouping, and partition operations.
Best for: Data processing and transformation pipelines
#kotlin#collections