foreach in kotlin
Asked Answered
A

4

41

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?

Ablation answered 19/4, 2012 at 11:50 Comment(3)
What page did you see it on? ThanksBiggers
@AndreyBreslav It's at the bottom of this page, and on this page and here in the closures section. I signed up for Confluence, but looks like you need special rights to alter the confluence wiki. Looks like someone spotted it on twitter as well ;-)Narcolepsy
There is still one, search Filter created a collection for us, and we called foreach() on that collectionAblation
M
63

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)
}
Mohn answered 5/6, 2019 at 22:7 Comment(1)
Is this thread-safe? I haven't found information on this.Squeaky
N
24

It needs a capital E in forEach ie:

fun main(args : Array<String>) {
    args.asList().filter { it -> it.length > 0 }.forEach { println("Hello, $it!") }
}
Narcolepsy answered 19/4, 2012 at 14:1 Comment(3)
doesn't compile .. aren't the dots needed? or am i hallucinating early in the a.m.Copybook
also it compllains about the parentheses after lengthCopybook
updated... things must have moved on...Narcolepsy
B
6

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")
    }
Bazemore answered 18/4, 2018 at 7:25 Comment(0)
H
0

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")
    }
}
Huck answered 25/7 at 10:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.