user1002430
user1002430

Reputation:

Scala xs.foreach(yield _)?

Learning about Scala and confused with the following:

Assume this: val filesHere = (new java.io.File(".")).listFiles

This works: for (fn <- filesHere) yield fn

This works: filesHere.foreach(println _)

This doesn't work: filesHere.foreach(yield _)

The error message is: <console>:1: error: illegal start of simple expression

Why doesn't the last one work and how to get it to work using foreach?

Upvotes: 1

Views: 3329

Answers (1)

PermaFrost
PermaFrost

Reputation: 1446

yield is a keyword that is used only in combination with for comprehensions, i.e. for (fn <- filesHere) yield fn in your example code. This will iterate over filesHere and return each element via yield fn.

The following would then assign the resulting collection of fnelements to the value result:

val result = for (fn <- filesHere) yield fn

for (fn <- filesHere) yield fn is equivalent to filesHere.map(fn => fn).

filesHere.foreach(fn => fn) would be equivalent to for (fn <- filesHere) fn (i.e. no yield keyword and thus no result element returned, which means it would in your case not do anything useful.

For completeness: filesHere.foreach(println _) is equivalent to filesHere.foreach(fn => println(fn)) which does something more useful by printing to the standard output via println.

Hope this clarifies it a bit :).

Upvotes: 5

Related Questions