21

What is the difference (if any) between two code fragments below?

Example from Ch7 of Programming i Scala

def grep(pattern: String) = 
  for (
    file <- filesHere
    if file.getName.endsWith(".scala");
    line <- fileLines(file)
    if line.trim.matches(pattern)
  ) println(file + ": " + line.trim)

and this one

def grep2(pattern: String) = 
  for (
    file <- filesHere
    if file.getName.endsWith(".scala")
  ) for (
    line <- fileLines(file)
    if line.trim.matches(pattern)
  ) println(file + ": " + line.trim)

Or

for (i <- 1 to 2)
  for (j <- 1 to 2)
    println(i, j)

and

for (
  i <- 1 to 2;
  j <- 1 to 2
) println(i, j)
2
  • 2
    I think the variants only differ by syntax. Section 6.19 of the Scala Language Specification (v. 2.8) defines how for loops are rewritten. scala-lang.org/sites/default/files/linuxsoft_archives/docu/… Commented Sep 3, 2010 at 11:06
  • Search for questions about Scala and yield. One of them should explain exactly how for works in Scala. Commented Sep 3, 2010 at 18:40

2 Answers 2

37

In this case there is no difference. However when using yield there is:

for (
  i <- 1 to 2;
  j <- 1 to 2
) yield (i, j)

Will give you a sequence containing (1,1), (1,2), (2,1) and (2,2).

for (i <- 1 to 2)
  for (j <- 1 to 2)
    yield (i, j)

Will give you nothing, because it generates the sequence (i,1), (i,2) on each iteration and then throws it away.

Sign up to request clarification or add additional context in comments.

Comments

12

Sometimes it is also useful to output a multi dimensional collection (for example a matrix of table):

for (i <- 1 to 2) yield for (j <- 1 to 2) yield (i, j)

Will return:

Vector(Vector((1,1), (1,2)), Vector((2,1), (2,2)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.