ChapterÂ 3.Â Expressions and Conditionals
This chapter focuses on Scalaâs expressions, statements, and conditionals. The term expression as used in this book indicates a unit of code that returns a value after it has been executed. One or more lines of code can be considered an expression if they are collected together using curly braces (
}). This is known as an expression block.
Expressions provide a foundation for functional programming because they make it possible to return data instead of modifying existing data (such as a variable). This enables the use of immutable data, a key functional programming concept where new data is stored in new values instead of in existing variables. Functions, of course, can be used to return new data, but they are in a way just another type of expression.
When all of your code can be organized (or conceptualized) into a collection of one or more hierarchical expressions that return values using immutable data will be straightforward. The return values of expressions will be passed to other expressions or stored into values. As you migrate from using variables, your functions and expressions will have fewer side effects. In other words, they will purely act on the input you give them without affecting any data other than their return value. This is one of the main goals and benefits of functional programming.
As noted earlier, an expression is a single unit of code that returns a value.
Letâs start out with an example of a simple ...
Get Learning Scala now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.