Desktop version

Home arrow Computer Science arrow Building Applications with Scala

Source

Basic for loop in Scala REPL

We will see how to use basic for loop 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>for ( i <- 1 to 10)

| println("i * " + i + " = " + i * 10) i * 1 = 10

i * 2 = 20

i * 3 = 30

i * 4 = 40

i * 5 = 50

i * 6 = 60

i * 7 = 70

i * 8 = 80

i * 9 = 90

i * 10 = 100 scala>

Right now, we will create a for loop using a Scala data structure called List. This is very useful, because in the first line of code, you can define a List as well as set its values in the same line. Since we are using the List structure, you don't need to pass any other argument besides the List itself.

For with List in Scala REPL

We will see how to use for with List 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 listOfValues = List(1,2,3,4,5,6,7,8,9,10)

listOfValues: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala>for ( i<- listOfValues ) println(i)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

scala>

Next, we can use for loops with if statements in order to apply some filtering. Later in this book, we will approach a more functional way to approach filtering using functions. For this code, let's say we want to get just the even numbers on the list and print them.

For with if statements for filtering - Scala REPL

We will see how to use for with if statements 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 listOfValues = List(1,2,3,4,5,6,7,8,9,10)

listOfValues: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala>for ( i<- listOfValues ) if (i % 2== 0) println(i)

  • 2
  • 4
  • 6
  • 8
  • 10

scala>

Java code for filtering even numbers

In Scala language, we just need two lines of code to perform this filtering, whereas in Java it would have required at least eleven lines of code as you see in the following code:

package scalabook.javacode.chapl;

import java.util.Arrays; import java.util.List;

public class ForLoopsEvenNumberFiltering { public static void main(String[] args) {

List listOfValues = Arrays.asList( new Integer[]{1,2,3,4,5,6,7,8,9,10}); for(Integer i : listOfValues){

if (i%2==0) System.out.println(i);

}

}

}

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

Related topics