Scala:将字符串转换为 Int 或 None [英] Scala: convert string to Int or None

查看:30
本文介绍了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 或 None 的干净方法是什么?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆