Reputation: 198198
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
Reputation: 17
There are typos and writing errors in the code you wrote
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
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
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
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