Desktop version

Home arrow Computer Science arrow Building Applications with Scala


For comprehensions

Also known as list or sequence comprehensions, for comprehensions are one of the FP ways to perform loops. This is a language support to create List structure or collections based on other collections. This task is performed in a SetBuilder notation. Another way to accomplish the same goal would be by using the Map and filter functions, which we will cover later in this chapter. For comprehensions can be used in a generator form, which would introduce new variables and values, or in a reductionist way, which would filter values resulting into a new collection or sequence. The syntax is: for (expt) yield e, where the yield operator will add new values to a new collection/sequence that will be created from the original sequence.

For comprehension in Scala REPL

We will see how to use for comprehension in Scala REPL as follows:

$ scala

Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77). Type in expressions for evaluation. Or try :help.

scala>val names = Set("Diego", "James", "John", "Sam", "Christophe") names: scala.collection.immutable.Set[String] = Set(John, Sam, Diego,

James, Christophe) scala>

scala>val brazilians = for {

| name <- names

| initial <- name.substring(0, 1)

| } yield if (name.contains("Die")) name

brazillians: scala.collection.immutable.Set[Any] = Set((), Diego) scala>

In the preceding code, we create a set of names. As you can see, Scala, by default, prefers immutable data structures and uses immutable.Set. When we apply the for loop, we are simply filtering only the names which contain a specific substring, and then, using the yield operator, we are creating a new Set structure. The yield operator will keep the structure you are using. For instance, if we use List structure, it would create a List instead of a Set structure, the yield operator will always keep the same data collection you have on the variable. Another interesting aspect of the preceding code is the fact that we are holding the result of the for comprehension in a variable called Brazilians. Java does not have for comprehensions, but we could use similar code although it would require way more lines of code.

Java code for performing filtering with collections

We will see how to use Java code for performing filtering with collections as follows:

package scalabook.javacode.chapl;

import java.util.LinkedHashSet; import java.util.Set;

public class JavaNoForComprehension {

public static void main(String[] args) {

Set names = new LinkedHashSet<>();

Set brazillians = new LinkedHashSet<>();






for (String name: names){

if (name.contains("Die")) brazillians.add(name);





Found a mistake? Please highlight the word and press Shift + Enter  
< Prev   CONTENTS   Next >

Related topics