.toint
Scala : How do I convert a?String?to?Int?in Scala?
Solution: Use ‘toInt’
If you need to convert a?String?to an?Int?in?Scala, just use the?toInt?method, which is available on?String?objects, like this:
scala> val i = "1".toInt i: Int = 1As you can see, I?just cast the string?"1"?to an?Int?object using the?toInt?method, which is available to any?String.
However, beware that this can fail with a?NumberFormatException?just like it does in Java, like this:
?
scala> val i = "foo".toInt java.lang.NumberFormatException: For input string: "foo"so you’ll want to account for that in your code, such as with a try/catch statement.
A Java-like String to Int conversion function
The following functions show a couple of ways you can handle the exception that can be thrown in the string to int conversion process. This first example shows the “Java” way to write a?String?to?Int?conversion function:
def toInt(s: String): Int = {try {s.toInt} catch {case e: Exception => 0} }That function returns the correct int value if the string can be converted to an int (such as "42"), and returns 0 if the string is something else, like the string "foo".
A Scala “String to Int” conversion function that uses Option
A more "Scala like" way to write a string to int conversion function looks like this:
def toInt(s: String): Option[Int] = {try {Some(s.toInt)} catch {case e: Exception => None} }?
This function returns a?Some(Int)?if the string is successfully converted to an int, and a?None?if the string could not be converted to an integer. This function is shown in the following REPL examples:
scala> val x = toInt("foo") x: Option[Int] = Nonescala> val x = toInt("10") x: Option[Int] = Some(10)As I wrote in?my book about Scala and functional programming, you can also write a Scala?toInt?function that uses?Try,?Success, and?Failure?like this:
import scala.util.{Try, Success, Failure} def makeInt(s: String): Try[Int] = Try(s.trim.toInt)You can also return an?Option?like this:
import scala.util.control.Exception._ def makeInt(s: String): Option[Int] = allCatch.opt(s.toInt)Please see?my Scala Option/Some/None idiom tutorial?for more ways to use these patterns, and to use the?Option?and?Try?results.
總結
- 上一篇: html 文字 向上滚动代码,文字向上滚
- 下一篇: 相信积累的力量——《把时间当作朋友》读后