Scala:将字符串转换为Int或None [英] Scala: convert string to Int or None
本文介绍了Scala:将字符串转换为Int或None的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从xml字段中获取一个数字
I am trying to get a number out of an xml field
...
<Quantity>12</Quantity>
...
通过
Some((recipe \ "Main" \ "Quantity").text.toInt)
有时在xml中可能没有值。文本将是,这会抛出一个java.lang.NumberFormatException。
Sometimes there may not be a value in the xml, though. The text will be ""
and this throws an java.lang.NumberFormatException.
什么是干净的方式获取Int或无?
What is a clean way to get either an Int or a None?
推荐答案
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
这篇关于Scala:将字符串转换为Int或None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文