For Expressions

Learn about “for expressions” in Scala.

We'll cover the following

For loops?

The for expression in Scala is a very powerful feature. It can be used similar to a normal “for loop” but can also be used for parallel programming and to avoid null-pointer exceptions.

First, we will discuss how to avoid null-pointer exceptions. Scala has Option for this, which has two implementations: Some and None. Some wrapping a value, and None representing a null value.

For example, imagine we want to create a Person object only if firstName and surname are supplied. Then using the scala command-line, define the Person class:

scala> case class Person(firstName: String, surname: String)
defined class Person

Define maybeFirstname and maybeSurname as instances of Option with None for maybeSurname (meaning it was not supplied).

Let’s see this below:

Get hands-on with 1400+ tech skills courses.