Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Some sample code regarding Scala Vs Java code verbosity

JAVA

List<Integer> even = new ArrayList<Integer>();
for (String num : numbersAsStrings) {
 int parsedInt = Integer.parseInt(num);
 if (parsedInt % 2 == 0) {
  ints.add(parsedInt);
 }
} 

Scala

Several way to do this in scala

val ints = for (num <- numbersAsStrings; if num.toInt % 2 == 0) yield num.toInt
val ints = numbersAsStrings map { _.toInt } filter {_ % 2 == 0}

Contributed by Rodolfo Hansen @kryptt

val ints = numbersAsString.foldLeft(List[Int]()) { (arr, str) => val n = str.toInt; if (n % 2 == 0) n::arr else arr };
val ints = numbersAsString.foldLeft(List[Int]()) { (arr, str) => ((n:Int) => if (n % 2 == 0) n::arr else arr )(str.toInt) };
val ints = for { s <- numbersAsString; i = s.toInt; if i % 2 == 0} yield i;
val ints = numbersAsString collect { _.toInt match { case n if (n % 2 == 0) => n } }

Contributed by Iain McGinniss @iainmcgin

val ints = (numbersAsStrings.view map { _.toInt } filter {_ % 2 == 0}).force
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.