Introduction
Scala is both an object-oriented programming (OOP) and a functional
programming (FP) language. This chapter demonstrates functional
programming techniques, including the ability to define functions and pass
them around as instances. Just like you create a String
instance in Java and pass it around, you
can define a function as a variable and pass it around. I’ll demonstrate
many examples and advantages of this capability in this chapter.
As a language that supports functional programming, Scala encourages
an expression-oriented programming
(EOP) model. Simply put, in EOP, every statement (expression)
yields a value. This paradigm can be as obvious as an if
/else
statement returning a value:
val
greater
=
if
(
a
>
b
)
a
else
b
It can also be as surprising as a try
/catch
statement returning a value:
val
result
=
try
{
aString
.
toInt
}
catch
{
case
_
=>
0
}
Although EOP is casually demonstrated in many examples in this book, it’s helpful to be consciously aware of this way of thinking in the recipes that follow.
Get Scala Cookbook 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.