0

In the following code :

val expression : String = "1+1";
     for (expressionChar <- expression) {
      println(expressionChar)
    }

the output is "1+1"

How is each character being accessed here ? What is going on behind the scenes in Scala. Using Java I would need to use the .charAt method , but not in Scala, why ?

blue-sky
  • 51,962
  • 152
  • 427
  • 752
  • As far as I remember, if there's no `yield`, the for-comprehension turns into `foreach`, so you're effectively doing `expression.foreach(println(_))`, or more verbose version: `expression.foreach(character => println(character))` (if there's a `yield`, then it's `flatMap`, right?) as string is a collection or, more precisely, a sequence of characters . I'm not 100% sure that's the exact mechanism though, so I'll wait for someone more oriented in the topic to chime in :) – Patryk Ćwiek Apr 20 '13 at 11:48
  • The reason that you need to use `charAt` in Java, is that strings aren't iterable in Java, so you have to create an index variable and loop with that. If they were iterable, you could write `for(char expressionChar : expression)` (like you can with arrays of collections already) pretty much like in Scala. – sepp2k Apr 20 '13 at 12:23

2 Answers2

4

In scala, a for comprehension:

for (p <- e) dosomething

would be translated to

e.foreach { x => dosomething } 

You can look into Scala Reference 6.19 for more details. However, String in scala is just a Java String, which doesnot have a method foreach. But there is an implicit conversion defined in Predef which convert String to StringOps which indeed have a foreach method.

So, finally the code for(x <- "abcdef") println(x) be translated to:

Predef.augmentString("abcdef").foreach(x => println(x))

You can look int the scala reference or Scala Views for more information.

Randall Schulz
  • 26,420
  • 4
  • 61
  • 81
Eastsun
  • 18,526
  • 6
  • 57
  • 81
2
scala> for (c <- "1+1") println(c)
1
+
1

Is the same as

scala> "1+1" foreach (c => println(c))
1
+
1

Scalas for-comprehension is not a loop but a composition of higher order functions that operate on the input. The rules on how the for-comprehension is translated by the compiler can be read here.

Furthermore, in Scala Strings are collections. Internally they are just plain old Java Strings for which there exists some implicit conversions to give them the full power of the Scala collection library. But for users they can be seen as collections.

In your example foreach iterates over each element of the string and executes a closure on them (which is the body of the for-comprehension or the argument in the foreach call).

Even more information about for-comprehensions can be found in section 7 of the StackOverflow Scala Tutorial.

Community
  • 1
  • 1
kiritsuku
  • 52,967
  • 18
  • 114
  • 136