for loop kotlin

  for loops are similar to Java, but the syntax is different. Kotlin for loops are not expressions.

Kotlin for loops have this basic syntax:

for (e in elements) { // do something with e …}

For example, given a list:

val nums = listOf(1,2,3)

here’s a single-line algorithm:

for (n in nums) println(n)

The REPL shows how it works:

>>> for (n in nums) println(n)




You can also use multiple lines of code in your algorithm:

for (n in 1..3) {



Here are a couple of other examples:

// directly on listOf

for (n in listOf(1,2,3)) println(n)

// 1..3 creates a range for (n in 1..3) println(n)

Using  for  with Maps

You can also use a for loop with a Kotlin Map (Like the hashmap in Java ). Here is a “Map” of movies and their ratings:

val ratings = mapOf(

“Mars” to 3.0, “Beautiful mind” to 4.0, “Interstellar” to 4.5


Given that map, you can print the movie names and ratings with this for loop:

for ((name,rating) in ratings) println(“Movie: $name, Rating: $rating”)

Here’s what that looks like in the REPL:

>>> for ((name,rating) in ratings) println(“Movie: $name, Rating: $rating”) Movie: Mars, Rating: 3.0

Movie: Beautiful mind, Rating: 4.0 Movie: Interstellar, Rating: 4.5

In this example, name corresponds to each key in the map, and rating is the name I assign for each value in the map

  for  is not an expression

We said previously that for is not an expression in opposite to Scala language. That means that code like this does not work:

// error

val x = for (n in 1..3) { return n * 2


اترك تعليقاً

لن يتم نشر عنوان بريدك الإلكتروني. الحقول الإلزامية مشار إليها بـ *

جميع الحقوق محفوظة لموقع كيفاش 2021