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?
Definition and Usage The forEach() method calls a function for each element in an array.
We can use the listIterator() method for iterating through lists in both forward and backward directions.
In Kotlin, we cannot explicitly use break and continue statements explicitly inside a forEach loop, but we can simulate the same action.
In computer programming, foreach loop (or for each loop) is a control flow statement for traversing items in a collection. foreach is usually used in place of a standard for loop statement.
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!") }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With