BoldRadius' Senior Software Developer Alejandro Lujan explains how to use higher order functions in Scala and illustrates them with some examples.
See the accompanying video at www.boldradius.com/blog
2. Higher
order
func2ons
• Allow
behavior
to
be
passed
in
as
arguments
• Return
func2ons
from
method
calls
• Allows
for
more
abstract
constructs
=>
more
library-‐like,
requiring
less
maintenance
3. Example:
Filter
• Set[A]
contains
a
method
called
filter:
filter(p: A => Boolean): Set[A]
• Use
it
to
select
elements
that
comply
with
a
predicate
4. Example:
Filter
val set = (-10 to 10).toSet
def isEven(i:Int) = i % 2 == 0
// Set[A].filter(p: A => Boolean): Set[A]
set.filter(i => isEven(i))
set.filter(isEven(_))
set.filter(isEven)
5. Example:
Map
• List[A]
contains
a
method
called
map:
map[B](f: A => B): List[B]
• Use
it
to
transform
each
element
in
the
list
by
applying
f
6. Example:
Map
def capitalize(s: String) =
s.head.toUpper + s.tail.toLowerCase
val list = List("samwise", "meriadoc",
"peregrin")
list.map(capitalize)
7. Some
interes2ng
examples
• Collec2ons
– best
implementa2on
depends
on
collec2on:
recursive,
itera2ve,
with
auxiliary
mutable
state.
• Parallel
collec2ons
– interface
is
fundamentally
the
same,
paralleliza2on
is
hidden
from
you.
• Futures
– transform
the
value
once
it's
available