Skip to content

Instantly share code, notes, and snippets.

@Mortimerp9
Last active December 13, 2015 22:39
Show Gist options
  • Save Mortimerp9/4985630 to your computer and use it in GitHub Desktop.
Save Mortimerp9/4985630 to your computer and use it in GitHub Desktop.
Java vs Scala list operation from Raúl Raja Martínez + dealing with an exception

JAVA

List<Integer> even = new ArrayList<Integer>();
for (String num : numbersAsStrings) {
 try {
  int parsedInt = Integer.parseInt(num);
  if (parsedInt % 2 == 0) {
    ints.add(parsedInt);
  }
 } catch(NumberFormatException e) {
   //ignore the exception (you might want to log it)
 }
} 

SCALA

one way to do it, using the standard tools from scala.util.control.Exception

import  scala.util.control.Exception._
val numbersAsStrings = Seq("1", "2", "3", "4", "10", "N")
val ints = numbersAsStrings flatMap { catching(classOf[NumberFormatException]) opt _.toInt } filter { _ % 2 == 0 }

catching(classOf[NumberFormatException]) opt is the main trick in this variation, as it catches the exceptions and instead returns an Option[Int], which is either Some(_.toInt) if it can be parsed, or None if it raises an exception. Because we do not want the Option wrapping at the end, we use flatMap instead of map, that gets rid of the None values.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment