The Kotlin for loop is a control flow structure designed to iterate through any object that provides an iterator. This includes ranges, arrays, collections, strings, and custom objects. The for loop iterates through anything that provides an iterator. This is equivalent to the foreach loop in languages like C#.
The fundamental syntax of a Kotlin for loop follows this pattern:
for (item in collection) {
// Code to execute for each item
}
Here’s what each component means:
One of the most common uses of Kotlin for loops is iterating through ranges. Ranges provide a clean way to work with sequences of numbers.
for (number in 1..5) {
println("Number: $number")
}
This example demonstrates how to iterate from 1 to 5 (inclusive). The ..
operator creates a closed range that includes both start and end values.
for (countdown in 10 downTo 1) {
println("Countdown: $countdown")
}
The downTo
function allows you to iterate in reverse order, perfect for countdown scenarios in Android apps.
for (evenNumber in 2..20 step 2) {
println("Even number: $evenNumber")
}
The step
keyword lets you specify custom increments, useful for processing data at specific intervals.
for (index in 0..<10) {
println("Index: $index")
}
An open-ended range, call the .rangeUntil() function with the ..< operator. This includes the start value but excludes the end value.
Arrays are fundamental data structures in Android development, and Kotlin for loops make array iteration straightforward.
val androidVersions = arrayOf("Marshmallow", "Nougat", "Oreo", "Pie", "Android 10")
for (version in androidVersions) {
println("Android Version: $version")
}
When you need both the index and value, use the indices
property:
val colors = arrayOf("Red", "Green", "Blue", "Yellow")
for (index in colors.indices) {
println("Color at index $index: ${colors[index]}")
}
val frameworks = arrayOf("Jetpack Compose", "React Native", "Flutter", "Xamarin")
for ((index, framework) in frameworks.withIndex()) {
println("[$index] $framework")
}
The withIndex()
function returns pairs of (index, value), making it perfect for scenarios where you need both pieces of information.
Kotlin for loops excel when working with various collection types commonly used in Android development.
val programmingLanguages = listOf("Kotlin", "Java", "Swift", "Dart")
for (language in programmingLanguages) {
println("Programming Language: $language")
}
val uniqueFeatures = setOf("Null Safety", "Coroutines", "Extension Functions", "Data Classes")
for (feature in uniqueFeatures) {
println("Kotlin Feature: $feature")
}
Maps require special handling since they contain key-value pairs:
val androidApiLevels = mapOf(
"Marshmallow" to 23,
"Nougat" to 24,
"Oreo" to 26,
"Pie" to 28,
"Android 10" to 29
)
// Iterate through keys
for (versionName in androidApiLevels.keys) {
println("Version: $versionName, API Level: ${androidApiLevels[versionName]}")
}
// Iterate through key-value pairs
for ((versionName, apiLevel) in androidApiLevels) {
println("$versionName has API Level $apiLevel")
}
Strings in Kotlin are iterable, allowing character-by-character processing:
val appName = "MyAndroidApp"
for (character in appName) {
println("Character: $character")
}
You can also iterate through string indices:
val packageName = "com.example.myapp"
for (index in packageName.indices) {
println("Character at position $index: ${packageName[index]}")
}
Nested loops are useful for processing multi-dimensional data:
val matrix = arrayOf(
arrayOf(1, 2, 3),
arrayOf(4, 5, 6),
arrayOf(7, 8, 9)
)
for (row in matrix) {
for (element in row) {
print("$element ")
}
println()
}
Kotlin supports traditional break and continue operators in loops.
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
// Skip even numbers
for (number in numbers) {
if (number % 2 == 0) continue
println("Odd number: $number")
}
// Stop at first number greater than 5
for (number in numbers) {
if (number > 5) break
println("Number: $number")
}
When working with data classes or pairs, destructuring simplifies access to properties:
data class User(val id: Int, val name: String, val email: String)
val users = listOf(
User(1, "Alice", "alice@example.com"),
User(2, "Bob", "bob@example.com"),
User(3, "Charlie", "charlie@example.com")
)
for ((id, name, email) in users) {
println("User $id: $name ($email)")
}
data class ApiResponse(val id: Int, val title: String, val completed: Boolean)
val apiResponses = listOf(
ApiResponse(1, "Complete login feature", true),
ApiResponse(2, "Implement dark theme", false),
ApiResponse(3, "Add push notifications", true)
)
for (response in apiResponses) {
val status = if (response.completed) "✓ Completed" else "⏳ Pending"
println("Task ${response.id}: ${response.title} - $status")
}
data class ListItem(val title: String, val subtitle: String, val imageUrl: String)
val recyclerViewItems = mutableListOf<ListItem>()
val rawData = listOf("Item 1", "Item 2", "Item 3", "Item 4", "Item 5")
for ((index, title) in rawData.withIndex()) {
recyclerViewItems.add(
ListItem(
title = title,
subtitle = "Subtitle for $title",
imageUrl = "https://example.com/image_$index.jpg"
)
)
}
data class DatabaseRecord(val id: Long, val name: String, val timestamp: Long)
val databaseRecords = listOf(
DatabaseRecord(1L, "Record One", System.currentTimeMillis()),
DatabaseRecord(2L, "Record Two", System.currentTimeMillis()),
DatabaseRecord(3L, "Record Three", System.currentTimeMillis())
)
for (record in databaseRecords) {
println("Processing record ${record.id}: ${record.name}")
// Perform database operations
}
Here’s a comprehensive example that demonstrates multiple Kotlin for loop concepts in a practical Android context:
import kotlin.random.Random
fun main() {
println("=== Kotlin For Loop Demo for Android Development ===\n")
// 1. Range iteration for progress tracking
println("1. Loading Progress:")
for (progress in 0..100 step 10) {
println("Loading... $progress%")
}
println()
// 2. Array iteration for UI components
println("2. UI Component Processing:")
val uiComponents = arrayOf("Button", "TextView", "EditText", "ImageView", "RecyclerView")
for ((index, component) in uiComponents.withIndex()) {
println("Component ${index + 1}: $component")
}
println()
// 3. List iteration for user data
println("3. User Data Processing:")
data class User(val id: Int, val name: String, val isActive: Boolean)
val users = listOf(
User(1, "John Doe", true),
User(2, "Jane Smith", false),
User(3, "Mike Johnson", true),
User(4, "Sarah Wilson", true)
)
var activeUsers = 0
for (user in users) {
val status = if (user.isActive) "Active" else "Inactive"
println("User ${user.id}: ${user.name} - $status")
if (user.isActive) activeUsers++
}
println("Total active users: $activeUsers\n")
// 4. Map iteration for configuration settings
println("4. App Configuration:")
val appConfig = mapOf(
"theme" to "dark",
"language" to "en",
"notifications" to "enabled",
"location" to "disabled"
)
for ((setting, value) in appConfig) {
println("$setting: $value")
}
println()
// 5. String iteration for input validation
println("5. Input Validation:")
val userInput = "MyApp123"
var hasDigits = false
var hasLetters = false
for (char in userInput) {
when {
char.isDigit() -> hasDigits = true
char.isLetter() -> hasLetters = true
}
}
println("Input: $userInput")
println("Contains digits: $hasDigits")
println("Contains letters: $hasLetters")
println("Valid format: ${hasDigits && hasLetters}\n")
// 6. Nested loops for matrix operations
println("6. Grid Layout Processing:")
val gridSize = 3
val grid = Array(gridSize) { row ->
Array(gridSize) { col ->
Random.nextInt(1, 10)
}
}
for (row in grid.indices) {
for (col in grid[row].indices) {
print("${grid[row][col]} ")
}
println()
}
println()
// 7. Break and continue example
println("7. Error Handling with Break/Continue:")
val networkResponses = listOf(200, 404, 500, 200, 301, 200)
for (responseCode in networkResponses) {
when {
responseCode == 500 -> {
println("Critical error encountered (500). Stopping processing.")
break
}
responseCode >= 400 -> {
println("Client error ($responseCode). Skipping...")
continue
}
else -> {
println("Success response: $responseCode")
}
}
}
}
Expected Output:
=== Kotlin For Loop Demo for Android Development ===
1. Loading Progress:
Loading... 0%
Loading... 10%
Loading... 20%
Loading... 30%
Loading... 40%
Loading... 50%
Loading... 60%
Loading... 70%
Loading... 80%
Loading... 90%
Loading... 100%
2. UI Component Processing:
Component 1: Button
Component 2: TextView
Component 3: EditText
Component 4: ImageView
Component 5: RecyclerView
3. User Data Processing:
User 1: John Doe - Active
User 2: Jane Smith - Inactive
User 3: Mike Johnson - Active
User 4: Sarah Wilson - Active
Total active users: 3
4. App Configuration:
theme: dark
language: en
notifications: enabled
location: disabled
5. Input Validation:
Input: MyApp123
Contains digits: true
Contains letters: true
Valid format: true
6. Grid Layout Processing:
7 2 4
1 9 3
6 8 5
7. Error Handling with Break/Continue:
Success response: 200
Client error (404). Skipping...
Critical error encountered (500). Stopping processing.
This comprehensive example showcases how Kotlin for loops integrate seamlessly into Android development workflows, from basic iteration to complex data processing scenarios. The elegant syntax and powerful features make Kotlin for loops an essential tool for any Android developer looking to write clean, efficient code.