Back to Web Development
2026-03-298 min read

Kotlin For Loop (Web Development)

Learn Kotlin For Loop (Web Development) step by step with clear examples and exercises.

Why This Matters

Why This Matters (Expanded)

In web development, loops are essential for handling repetitive tasks such as iterating through arrays, lists, or collections of data. While JavaScript is commonly used for front-end development, Kotlin, a modern JVM language, offers a more concise and efficient way to handle loops in web applications. This lesson will help you understand the Kotlin For Loop and how it can be beneficial for your web development projects.

Kotlin's For Loop provides several advantages over traditional JavaScript loops:

  1. Conciseness: The Kotlin For Loop syntax is more concise, making your code cleaner and easier to read.
  2. Type Safety: Kotlin offers strong type safety, which can help you catch errors at compile-time instead of runtime.
  3. Interoperability: Since Kotlin runs on the Java Virtual Machine (JVM), it seamlessly integrates with existing Java libraries and frameworks used in web development.
  4. Improved Performance: Kotlin's For Loop can offer better performance than JavaScript loops due to its optimized JVM implementation.

Prerequisites

Before diving into the Kotlin For Loop, ensure you have a good understanding of:

  1. Basic Kotlin syntax (variables, functions, data types)
  2. HTML/CSS fundamentals (HTML structures, CSS selectors)
  3. Web development concepts (HTTP requests, web servers, front-end frameworks)
  4. Familiarity with the Kotlin Standard Library and any additional libraries you plan to use in your project.

Core Concept

The Kotlin For Loop is a control structure used to iterate over a collection of items, such as arrays, lists, or maps. It provides a more concise and readable way to handle repetitive tasks compared to traditional JavaScript loops like for, while, or do-while loops.

Syntax

The basic syntax for the Kotlin For Loop is:

for (item in collection) {
// code block to execute for each item
}

Here's a breakdown of the syntax:

  • item: A variable that holds the current element from the collection on each iteration.
  • collection: The data structure containing the items you want to iterate over, such as an array, list, or map.
  • // code block: The block of code that will be executed for each item in the collection.

Iterating through arrays and lists

Let's consider an example where we have an array of strings and we want to print each element:

fun main() {
val fruits = arrayOf("apple", "banana", "orange")

for (fruit in fruits) {
println(fruit)
}
}

Output:

apple
banana
orange

Iterating through maps

In addition to arrays and lists, you can also iterate through maps using the Kotlin For Loop. Here's an example where we have a map of fruits and their prices, and we want to print each item:

fun main() {
val fruitPrices = mapOf(
"apple" to 1.5,
"banana" to 0.75,
"orange" to 2.0
)

for ((key, value) in fruitPrices) {
println("$key: $value")
}
}

Output:

apple: 1.5
banana: 0.75
orange: 2.0

Worked Example

In this example, we will create a simple web application that fetches data from an API and displays it using the Kotlin For Loop. We'll use the kotlinx.html library for HTML generation and ktor for HTTP requests.

First, add the required dependencies to your build.gradle file:

dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
implementation "org.jetbrains.kotlin:kotlin-reflect"
implementation "io.ktor:ktor-client-core"
implementation "io.ktor:ktor-client-cio"
implementation "io.ktor:ktor-client-content-negotiation"
implementation "io.ktor:ktor-client-logging"
implementation "org.jetbrains.kotlinx:kotlinx-html:1.3.0"
}

Next, create a new Kotlin file for the main application and implement the following code:

import io.ktor.application.*
import io.ktor.features.ContentNegotiation
import io.ktor.features.logging.logging
import io.ktor.http.content.TextContent
import io.ktor.request.get
import io.ktor.response.respondText
import io.ktor.client.HttpClient
import io.ktor.client.engine.CIO
import org.w3c.dom.Document
import org.w3c.dom.Element
import org.jetbrains.kotlinx.html.HTML
import org.jetbrains.kotlinx.html.JSXBuilder
import org.jetbrains.kotlinx.html.body
import org.jetbrains.kotlinx.html.head
import org.jetbrains.kotlinx.html.html
import org.jetbrains.kotlinx.html.js.onClickFunction

fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)

@Suppress("unused")
@KtorExperimentalAPI
class Application : ApplicationCallPipelineFactory<ApplicationCall, ApplicationCallParameters> {
override val features = listOf(ContentNegotiation, logging())

override fun create(block: ApplicationCall.() -> Unit) {
installedFeatures.logging.logger.info("Starting web server...")
HttpClient(CIO) {
install(ContentNegotiation) {
json()
}
}.use { client ->
val apiUrl = "https://jsonplaceholder.typicode.com/todos"

val response = client.get(apiUrl).body()
if (response.status == 200) {
val todos: List<Map<String, Any>> = response.readText().let { json ->
Json.parseToJsonElement(json).asJsonArray.map { it.asJsonObject }
}

html {
head {
title { +"Kotlin For Loop Example" }
}
body {
h1 { +"Todos from JSONPlaceholder API" }
ul {
for (todo in todos) {
val id = todo["id"] as Int
val title = todo["title"] as String
val completed = todo["completed"] as Boolean

li {
+"$id: $title (${if (completed) "Completed" else "Not Completed"})"
onClickFunction = { _ -> println("Todo with ID $id clicked!") }
}
}
}
}
}.toString()

call.respondText(TextContent(HTML), status = HttpStatusCode.OK)
} else {
call.respondText("Error fetching data from the API", status = HttpStatusCode.InternalServerError)
}
}
}

After running the application, you should see a simple web page displaying the todos fetched from the JSONPlaceholder API using the Kotlin For Loop.

Common Mistakes

  1. Forgetting to initialize the collection: Ensure that the collection you want to iterate over is properly defined before using it in the for loop.
  2. Iterating through an empty collection: Check if your collection contains any items before attempting to iterate over it, as this can lead to unexpected behavior or errors.
  3. Misunderstanding the iteration order: The Kotlin For Loop uses the default iteration order of the collection, which is usually not guaranteed to be in a specific order (e.g., arrays are ordered based on their indices). If you need a specific order, consider using a list or map instead and sorting it before iterating.
  4. Using the wrong variable name: Incorrectly naming the variable used to store each item during iteration can lead to confusion and errors. Make sure to use descriptive names that clearly indicate the type of data being stored.
  5. Not handling exceptions: If you're working with external resources like files or APIs, make sure to handle exceptions properly to ensure your application doesn't crash when an error occurs.
  6. Incorrectly accessing collection elements: Be aware that Kotlin uses zero-based indexing for arrays and lists, so the first element will have an index of 0. For maps, you should use the key to access the associated value.
  7. Not accounting for collection changes during iteration: If the collection being iterated over can change during the loop (e.g., by adding or removing elements), it may cause unexpected behavior or errors. To avoid this, consider using a copy of the original collection or use an immutable collection if possible.
  8. Using the For Loop inappropriately: The Kotlin For Loop is best suited for iterating over collections, but it can also be used with other types like ranges and sequences. Be mindful of when to use the For Loop and consider using other control structures like while or do-while loops when appropriate.

Practice Questions

  1. Write a Kotlin function that takes an array of integers as input and returns the sum of all even numbers using the For Loop.
  2. Given a list of strings, write a Kotlin function that sorts the list alphabetically using the For Loop and stores the sorted list in a new list.
  3. Write a Kotlin function that takes a map of student names and their scores as input and calculates the average score using the For Loop.
  4. Given an array of arrays, write a Kotlin function that finds the maximum number in each sub-array using the For Loop.
  5. Write a Kotlin web application that fetches data from a custom API and displays it using the For Loop, similar to the example provided earlier but with a different API endpoint.
  6. Write a Kotlin function that takes an array of integers as input and finds the second largest number using the For Loop.
  7. Given a list of strings, write a Kotlin function that removes duplicates using the For Loop and stores the unique list in a new list.
  8. Write a Kotlin function that takes a map of words and their frequencies as input and sorts the map by frequency using the For Loop.
  9. Given an array of arrays, write a Kotlin function that finds the sum of all numbers in each sub-array using the For Loop.
  10. Write a Kotlin web application that fetches data from multiple APIs concurrently using Kotlin coroutines and displays the results using the For Loop.

FAQ

  1. Why should I use Kotlin for web development instead of JavaScript?
  • Kotlin offers more concise syntax, better type safety, and interoperability with Java, making it a powerful choice for web development. It can help reduce the number of bugs in your code and make it easier to maintain over time.
  1. Can I use the Kotlin For Loop to iterate through maps in reverse order?
  • Yes, you can use the reversed() function on the map's keys to iterate through it in reverse order. Alternatively, you can create a copy of the map and sort it in descending order before iterating.
  1. How do I handle exceptions when working with external resources like files or APIs in Kotlin?
  • You can use try-catch blocks to handle exceptions, and make sure to check for errors before proceeding with your operations. It's also a good idea to validate the data you receive from APIs to ensure it's in the expected format.
  1. What are some best practices for writing clean and maintainable Kotlin code?
  • Follow good coding conventions, write clear and concise comments, break large functions into smaller ones, and use descriptive variable names. Also, consider using libraries like kotlinx.coroutines for asynchronous operations and kotlinx.serialization for handling data serialization and deserialization.
  1. Can I mix JavaScript and Kotlin in the same web application?
  • Yes, you can use both JavaScript and Kotlin in the same web application by leveraging the interoperability between them. However, it's recommended to keep the two languages separate for better maintainability and readability. You can use JavaScript for client-side logic and Kotlin for server-side logic, and communicate between them using AJAX requests or WebSockets.
Kotlin For Loop (Web Development) | Web Development | XQA Learn