How to match int int strings?

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 {
  // Some cases
  case "five" => 5
  case Int(i) => i // Fails
  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()
  }
}
+4
4

,

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

,

"1234" match {
  // Some cases
  case "five" => 5
  case Int(i) => i // works :)
  case _ => throw new RuntimeException()
}
+7

  "1234" match {
      case number if number.matches("\\d+") => println(s"yes its a numeric value  $number")
      case _                                => println("not a numeric value")
    }
+1

@Jasper-M , - . , @Jasper-M , .

, :

val matcher = "1234" match {
  case "five" => Some(BigInt(5L))
  case regex(t) => Some(BigInt(t))
  case _ => None
}
val result: Option[Int] = matcher.filter(_.isValidInt).map(_.toInt)

Option[Int]], Some Int, String None .

I would go with the @ Jasper-M approach and see the performance. If you notice anything, then consider exception-based approaches.

+1
source

Maybe you can use guard in the match?

"12312312313123" match {
   case s: String if s.isInt => "int"
   case _ => "no int"
}

implicit class IsInt(i: String){
  def isInt: Boolean = Try(i.toInt).isSuccess
}
0
source

Source: https://habr.com/ru/post/1673027/


All Articles