Scala:将字符串转换为 Int 或 None
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23811425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala: convert string to Int or None
提问by doub1eHyman
I am trying to get a number out of an xml field
我正在尝试从 xml 字段中获取一个数字
...
<Quantity>12</Quantity>
...
via
通过
Some((recipe \ "Main" \ "Quantity").text.toInt)
Sometimes there may not be a value in the xml, though. The text will be ""and this throws an java.lang.NumberFormatException.
但是,有时 xml 中可能没有值。文本将是"",这将引发 java.lang.NumberFormatException。
What is a clean way to get either an Int or a None?
获得 Int 或 None 的干净方法是什么?
回答by Régis Jean-Gilles
scala> import scala.util.Try
import scala.util.Try
scala> def tryToInt( s: String ) = Try(s.toInt).toOption
tryToInt: (s: String)Option[Int]
scala> tryToInt("123")
res0: Option[Int] = Some(123)
scala> tryToInt("")
res1: Option[Int] = None
回答by Xavier Guihot
Scala 2.13introduced String::toIntOption:
Scala 2.13介绍String::toIntOption:
"5".toIntOption // Option[Int] = Some(5)
"abc".toIntOption // Option[Int] = None
"abc".toIntOption.getOrElse(-1) // Int = -1
回答by elm
More of a side note on usage following accepted answer. After import scala.util.Try, consider
在接受的答案之后,更多关于使用的旁注。之后import scala.util.Try,考虑
implicit class RichOptionConvert(val s: String) extends AnyVal {
def toOptInt() = Try (s.toInt) toOption
}
or similarly but in a bit more elaborated form that addresses only the relevant exception in converting onto integral values, after import java.lang.NumberFormatException,
或类似但更详细的形式,仅解决在转换为整数值时的相关异常,之后import java.lang.NumberFormatException,
implicit class RichOptionConvert(val s: String) extends AnyVal {
def toOptInt() =
try {
Some(s.toInt)
} catch {
case e: NumberFormatException => None
}
}
Thus,
因此,
"123".toOptInt
res: Option[Int] = Some(123)
Array(4,5,6).mkString.toOptInt
res: Option[Int] = Some(456)
"nan".toInt
res: Option[Int] = None
回答by Caoilte
Here's another way of doing this that doesn't require writing your own function and which can also be used to lift to Either.
这是执行此操作的另一种方法,不需要编写自己的函数,也可用于将Either.
scala> import util.control.Exception._
import util.control.Exception._
scala> allCatch.opt { "42".toInt }
res0: Option[Int] = Some(42)
scala> allCatch.opt { "answer".toInt }
res1: Option[Int] = None
scala> allCatch.either { "42".toInt }
res3: scala.util.Either[Throwable,Int] = Right(42)
(A nice blog poston the subject.)
(关于这个主题的一篇很好的博客文章。)

