Why does a for loop sometimes returns a string and sometimes a IndexedSeq[Char]?

Hey there!
You see those lovely code snippets at the bottom? I would like to know why the first one is returning a String but the second doesn’t.

unknown

Thank you very much for help me understand this.

Regards,
Toorero.

I see only one snippet.

can you illustrate both input and output to a running copy of your code?
Also explain what it is supposed to do.
I tried typing it into Eclipse, Scala 12.x and got this result:

object SimpleTest extends App {
def crypt(key: String, message: String): String = {
val keyi = Integer.parseInt(key, 2)
for ( c <- message ) yield ( c ^ keyi).toChar
}

val r = crypt(“1101101” , “roger”)
println(“r = %s, class = %s”.format(r,r.getClass))
}
output:
r =
, class = class java.lang.String

Thanks

No, I see one screenshot of a single snippet, not actually a snippet I can paste in my editor, and definitely not two of them.

1 Like

unknown

That second snippet makes if very clear. The for with yield is just converted to a map here and generally map tried to produce a result that is as close as possible to what it is being called on. Your first example is calling map on a String. Your second example, because you called zipWithIndex, is calling map on an IndexedSeq[(Char, Int)]. This is why the first one produces a String and the second one gives you an IndexedSeq[Char]. The second one isn’t being run on a String at all.