All posts

How to Fix Rangeerror in Kotlin In Production

Learn how to diagnose and fix the rangeerror in Kotlin in production. Includes code examples and prevention tips.

Encountering a rangeerror while working with Kotlin? This guide covers the root cause, provides a working code example, and shows you how to prevent it from recurring.

What Causes RangeError

A RangeError in production in Kotlin occurs when a value falls outside its permitted range. Common triggers include:

  • Array or string index out of bounds
  • Invalid arguments to built-in functions (negative array sizes, invalid string indices)
  • Infinite recursion exceeding the maximum call stack size
  • Numeric overflow or underflow in calculations
  • Pagination parameters pointing past the end of a collection

How to Fix It

// Safe range operations in Kotlin
fun <T> List<T>.safeSubList(from: Int, to: Int): List<T> {
    val safeFrom = from.coerceIn(0, size)
    val safeTo = to.coerceIn(safeFrom, size)
    return subList(safeFrom, safeTo)
}

fun <T> List<T>.safeGet(index: Int, default: T): T =
    if (index in indices) this[index] else default

// Usage
val page = allUsers.safeSubList(offset, offset + pageSize)
val firstUser = page.safeGet(0, User.ANONYMOUS)

Use coerceIn to clamp values to valid ranges and extension functions for safe collection access.

Prevention Strategies

  • Validate all numeric inputs at API boundaries before they reach internal logic
  • Add depth limits to recursive algorithms as a safety net
  • Use safe accessor methods that return null/None/Option instead of throwing
  • Add upper bounds to user-supplied size parameters to prevent resource exhaustion

Catch RangeErrors before they hit production with [Bugsly](https://bugsly.dev) — get full stack traces and the exact value that was out of range for every error in your Kotlin app.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free