Freewind
Freewind

Reputation: 198198

foreach in kotlin

I see an example in the official site:

fun main(args : Array<String>) {
  args filter {it.length() > 0} foreach {print("Hello, $it!")}
}

But when I copied it to idea, it reports that foreach is a unresolved reference.

What's the right code?

Upvotes: 44

Views: 141630

Answers (4)

Kevin Malik Fajar
Kevin Malik Fajar

Reputation: 17

There are typos and writing errors in the code you wrote

  1. It should be args.filter instead of args filter
  2. For it.length() should use it.length
  3. There is a typo in foreach, it should be forEach

The following is the correct code:

fun main(args : Array<String>) {
    args.filter { it.length > 0 }.forEach { print("Hello, $it!") }
}

Here is an easy version to try forEach:

fun main() {
    val exampleArrayList = arrayListOf<String>("Car", "Motorcycle", "Bus", "Train")
    exampleArrayList.forEach { data ->
        println("Vehicle: $data")
    }
}

Upvotes: 1

tim_yates
tim_yates

Reputation: 171084

It needs a capital E in forEach ie:

fun main(args : Array<String>) {
    args.asList().filter { it -> it.length > 0 }.forEach { println("Hello, $it!") }
}

Upvotes: 24

Suragch
Suragch

Reputation: 511626

For other Kotlin newbees like me who are coming here just wanting to know how to loop through a collection, I found this in the documentation:

val names = listOf("Anne", "Peter", "Jeff")
for (name in names) {
    println(name)
}

Upvotes: 70

Shyam Kumar
Shyam Kumar

Reputation: 919

use this code:

  val nameArrayList = arrayListOf<String>("John", "mark", "mila", "brandy", "Quater") // ArrayList<String>
    nameArrayList.forEach {
        println("Name:$it")
    }

    val nameMutableList= mutableListOf<String>("John", "mark", "mila", "brandy", "Quater") // MutableList<String>
    nameMutableList.forEach {
        println("Name:$it")
    }

    val nameList= listOf<String>("John", "mark", "mila", "brandy", "Quater") // List<String>
    nameList.forEach {
        println("Name:$it")
    }

Upvotes: 6

Related Questions