public
Last active

Some sample code regarding Scala Vs Java code verbosity

  • Download Gist
ScalaVsJava.md
Markdown

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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.