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)
为什么会这样,并且有可能使用map和toInt完成此工作?
只需添加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)
| 归档时间: |
|
| 查看次数: |
33 次 |
| 最近记录: |