I am trying to get a number out of an xml field
... <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.
What is a clean way to get either an Int or a None?
A string can be converted to integer in Scala using the toInt method. This will return the integer conversion of the string. If the string does not contain an integer it will throw an exception with will be NumberFormatException. So, the statement: val i = "Hello".
Using Character.isDigit method returns true if the character is a number.
In Scala Either, functions exactly similar to an Option. The only dissimilarity is that with Either it is practicable to return a string which can explicate the instructions about the error that appeared.
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 2.13
introduced String::toIntOption
:
"5".toIntOption // Option[Int] = Some(5) "abc".toIntOption // Option[Int] = None "abc".toIntOption.getOrElse(-1) // Int = -1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With