1

I am confused about list of chars and int with scala. Here is my example :

scala> var s = "123456"
s: String = 123456

scala> s.map(_.toInt)
res0: scala.collection.immutable.IndexedSeq[Int] = Vector(49, 50, 51, 52, 53, 54)

scala> s.map(_.toInt).sum
res1: Int = 309

The chars are converted in ASCII code I assume, how to just transform a char in its value ?

Thank you

2 Answers 2

7

s.map(_.asDigit).sum is the correct Scala API method. The toInt will return the ASCI code of the symbol, instead of the numerical representation.

scala> "123456".map(_.asDigit).sum
res0: Int = 21
Sign up to request clarification or add additional context in comments.

Comments

3

You can use Character.getNumericValue(char) like

s.map(Character.getNumericValue(_))

Outputs

res2: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5, 6)

Another option, would be subtracting '0' like

s.map(_ - '0')

for the same result.

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.