O'Reilly logo

Learning Scala Programming by Vikash Sharma

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

For expressions

We would not be wrong, if we say that the for expressions are powerful constructs in Scala. For expressions let you traverse through any collection and perform operations such as filtering and yielding out new collections. We have already gone through this concept in Chapter 3, Shaping Up our Scala Program. Let's recall the example we saw:

object ForExpressions extends App { 
 
  val person1 = Person("Albert", 21, 'm') 
  val person2 = Person("Bob", 25, 'm') 
  val person3 = Person("Cyril", 19, 'f') 
  val persons = List(person1, person2, person3) 
 
  val winners = for { 
    person <- persons 
    age = person.age 
    name = person.name 
    if age > 20 
  } yield name 
 
  winners.foreach(println) 
 
} 
 
case class Person(name: String, age: Int, gender: Char) 

The result ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required