I am trying to figure out what is the best way for a template to match a string representation of an int in Scala. What I really want to do is something like this:
"1234" match {
case "five" => 5
case Int(i) => i
case _ => throw new RuntimeException()
}
One approach is this using regex. A potential problem is that it will not detect if the integer is too large to fit in an int.
val ISINT = "^([+-]?\\d+)$".r
"1234" match {
case "five" => 5
case ISINT(t) => t.toInt
case _ => throw new RuntimeException()
}
Another approach uses a function toIntthat returns Option(borrowed from this blog post ). This is good because it allows the standard library to find out if a string contains an integer. The problem is that it makes me nest in my logic, where I think it should be flat.
def toInt(s: String): Option[Int] = {
try {
Some(s.toInt)
} catch {
case e: Exception => None
}
}
"1234" match {
case "five" => 5
case t => toInt(t) match {
case Some(i) => i
case None => throw new RuntimeException()
}
}