Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach in kotlin

Tags:

foreach

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?

like image 379
Freewind Avatar asked Apr 19 '12 11:04

Freewind


People also ask

What is the use of forEach?

Definition and Usage The forEach() method calls a function for each element in an array.

How do I iterate list in Kotlin?

We can use the listIterator() method for iterating through lists in both forward and backward directions.

Can we use break in forEach in Kotlin?

In Kotlin, we cannot explicitly use break and continue statements explicitly inside a forEach loop, but we can simulate the same action.

How do you define forEach?

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.


2 Answers

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)
}
like image 86
Suragch Avatar answered Sep 25 '22 14:09

Suragch


It needs a capital E in forEach ie:

fun main(args : Array<String>) {
    args.asList().filter { it -> it.length > 0 }.forEach { println("Hello, $it!") }
}
like image 36
tim_yates Avatar answered Sep 22 '22 14:09

tim_yates