'Scala: match and parse an integer string?

I'm looking for a way to matching a string that may contain an integer value. If so, parse it. I'd like to write code similar to the following:

  def getValue(s: String): Int = s match {
       case "inf" => Integer.MAX_VALUE 
       case Int(x) => x
       case _ => throw ...
  }

The goal is that if the string equals "inf", return Integer.MAX_VALUE. If the string is a parsable integer, return the integer value. Otherwise throw.



Solution 1:[1]

This is better IMHO:

val IntRegEx = "(\\d+)".r
def getValue(s: String): Option[Int] =
  s match {
    case "inf"         => Some(Int.MaxValue)
    case IntRegEx(num) => Some(num.toInt)
    case _             => None
  }

getValue("inf")          // Some(2147483647)
getValue("123412")       // Some(123412)
getValue("not-a-number") // None

Of course, it doesn't throw any exceptions, but if you really want it, you may use:

getValue(someStr).getOrElse(error("NaN"))

Solution 2:[2]

You could use a guard:

def getValue(s: String): Int = s match {
  case "inf" => Integer.MAX_VALUE 
  case _ if s.matches("[+-]?\\d+")  => Integer.parseInt(s)
}

Solution 3:[3]

How about:

def readIntOpt(x: String) =
  if (x == "inf")
    Some(Integer.MAX_VALUE)
  else
    scala.util.Try(x.toInt).toOption

Solution 4:[4]

an improved version of James Iry's extractor:

object Int { 
  def unapply(s: String) = scala.util.Try(s.toInt).toOption 
} 

Solution 5:[5]

Since Scala 2.13 introduced String::toIntOption:

"5".toIntOption   // Option[Int] = Some(5)
"abc".toIntOption // Option[Int] = None

we can cast the String as an Option[Int] after checking if it's equal to "inf":

if (str == "inf") Some(Int.MaxValue) else str.toIntOption
// "inf"   =>   Option[Int] = Some(2147483647)
// "347"   =>   Option[Int] = Some(347)
// "ac4"   =>   Option[Int] = None

Solution 6:[6]

def getValue(s: String): Int = s match {
    case "inf" => Integer.MAX_VALUE 
    case _ => s.toInt
}


println(getValue("3"))
println(getValue("inf"))
try {
    println(getValue("x"))
}
catch {
    case e => println("got exception", e)
    // throws a java.lang.NumberFormatException which seems appropriate
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Xavier Guihot
Solution 2 cayhorstmann
Solution 3
Solution 4 David Portabella
Solution 5
Solution 6 agilefall