Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: convert string to Int or None

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?

like image 928
doub1ejack Avatar asked May 22 '14 15:05

doub1ejack


People also ask

How do I convert a string to an int in Scala?

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".

How do you check if a string is a number Scala?

Using Character.isDigit method returns true if the character is a number.

What is either in Scala?

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.


2 Answers

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 
like image 180
Régis Jean-Gilles Avatar answered Sep 17 '22 00:09

Régis Jean-Gilles


Scala 2.13 introduced String::toIntOption:

"5".toIntOption                 // Option[Int] = Some(5) "abc".toIntOption               // Option[Int] = None "abc".toIntOption.getOrElse(-1) // Int = -1 
like image 25
Xavier Guihot Avatar answered Sep 20 '22 00:09

Xavier Guihot