How to check if an input variable is Int in Scala?

Hi, I am reading input variables from "args", and I want to check if the input is integer. I followed this link

var param=0 ... args(j) match { ... case args(j): Int => param =args(j) ... } 

but this gives me an error:

 [error] '=>' expected but ':' found. [error] case args(j): Int => param =args(j) 

I can’t understand what the problem is!

+6
source share
4 answers

Try the following:

  val intRegex = """(\d+)""".r val param = args(j) match { case intRegex(str) => str.toInt case _ => 0 // or some other value, or an exception } 

You might want to use the argument parsing library.

Or, if you want to assign several parameters in one pass:

 for (arg <- args) { arg match { case intRegex(arg) => param = arg.toInt case p if Files.exists(Paths.get(p)) => path = Paths.get(p) case _ => // } 

But this is a pretty ugly solution. I highly recommend you use some library, for example. Scopt ( https://github.com/scopt/scopt ). You can spend some time before you get used to it, but it’s good - you won’t reinvent the wheel next time :)

+5
source
 val isInteger = Try(args(j).toInt).isSuccess 
+5
source

Using scala.util.Try is another possible way.

  Try( args(j).toInt ) { case Success(i) => //do something with int i case Failure(ex) => //error message } 
+4
source

You just don’t understand the compliance with the scala pattern, I suggest you look at it again. Here is a good introduction https://www.tutorialspoint.com/scala/scala_pattern_matching.htm

 param = args(j) match { case i:Int => i case _ => MyDefaultValueOrWhatever } 

edit: Fixed typo in URL

0
source

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


All Articles