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?
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?
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)
}
It needs a capital E
in forEach
ie:
fun main(args : Array<String>) {
args.asList().filter { it -> it.length > 0 }.forEach { println("Hello, $it!") }
}
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")
}
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")
}
}
© 2022 - 2024 — McMap. All rights reserved.
Filter created a collection for us, and we called foreach() on that collection
– Ablation