Home

getOrElse

GetOrElse is a method used in functional programming to provide a fallback value when a value is missing. In the Scala standard library, getOrElse is defined on the Option[T] type and is commonly used to handle optional values without throwing exceptions.

For an Option[A], the signature is def getOrElse[B >: A](or: => B): B. The method returns the contained

Examples illustrate its typical use. val x: Option[Int] = Some(3); x.getOrElse(0) yields 3. val y: Option[Int] = None;

Relation to other constructs: getOrElse complements map and flatMap for transforming options, and pairs with orElse

Notes: The by-name default enables lazy evaluation, which is important when the default is expensive to compute

value
when
the
option
is
Some(a).
If
the
option
is
None,
it
evaluates
the
argument
or
and
returns
that
default
value.
The
or
parameter
is
by-name,
meaning
the
default
is
computed
lazily
and
only
if
needed.
y.getOrElse(0)
yields
0.
A
lazy
default
can
be
provided
to
avoid
unnecessary
work,
such
as
val
s:
Option[String]
=
None;
s.getOrElse
{
computeDefault()
}
where
computeDefault()
is
invoked
only
when
the
option
is
None.
and
fold
to
supply
defaults
in
broader
control
flow.
It
is
a
common
pattern
in
Scala
and
appears
in
similar
forms
in
other
languages’
optional/maybe
types
(for
example,
Optional.orElse
in
Java,
or
Maybe
with
a
default
in
functional
libraries).
or
has
side
effects.
The
method
also
enforces
type
compatibility
through
its
type
parameter
B
>:
A.