Priyanka
Priyanka

Reputation: 51

Output of scala For loop

scala> var sum =0
sum: Int = 0

scala> val s = "hello"
s: String = hello

scala> for (i <-0 to s.length-1)
     | sum +=s(i)

scala> println (sum)
532

I am new to Scala. Can someone explain why I am getting 532 as output?

Upvotes: 1

Views: 150

Answers (1)

Mike Allen
Mike Allen

Reputation: 8249

You're adding the values (Unicode codepoints) of the characters in the string "hello".

To see these values, try this:

"hello".map(_.toInt)

will result in:

Vector(104, 101, 108, 108, 111)

These are the values you're adding.

Upvotes: 1

Related Questions