使用map和toInt将字符串转换为Scala中的数字集合

Krz*_*ski 2 string int scala type-conversion

我可以使用将一个数字字符串转换为int toInt

scala> "1".toInt
res1: Int = 1
Run Code Online (Sandbox Code Playgroud)

但是,当我map遍历字符并使用它们分别转换它们toInt时,我得到了它们的ASCII码:

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

为什么会这样,并且有可能使用maptoInt完成此工作?

pme*_*pme 5

只需添加toString您的map功能:

 "123".map(_.toString.toInt)
Run Code Online (Sandbox Code Playgroud)

正如Xavier解释的那样,String(-collection)的元素是Char-,因此只需再做String一次。

或者按照他的建议使用.asDigit

"123".map(_.asDigit)
Run Code Online (Sandbox Code Playgroud)

从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)
Run Code Online (Sandbox Code Playgroud)