Converting string to a collection of digits in Scala using map and toInt

Viewed 64

I am able to convert a single digit string to int using toInt:

scala> "1".toInt
res1: Int = 1

However, when I use map to iterate through the characters and convert them individually using toInt I am getting their ASCII codes:

scala> "123".map(_.toInt)
res2: scala.collection.immutable.IndexedSeq[Int] = Vector(49, 50, 51)

Why is that and is it possible to use map and toInt to accomplish this?

1 Answers

Just add toString in your map function:

 "123".map(_.toString.toInt)

As Xavier explained an element of a String(-collection) is a Char - so just make a String again.

Or use as he suggested .asDigit:

"123".map(_.asDigit)

From the Repl:

scala> "123".map(_.toInt)
res0: scala.collection.immutable.IndexedSeq[Int] = Vector(49, 50, 51)

scala> "123".map(_.toString.toInt)
res1: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3)

scala> "123".map(_.asDigit)
res2: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3)
Related