9.4. More Complex Functions
Problem
You want to define a method that takes a function as a parameter, and that function may have one or more input parameters, and may also return a value.
Solution
Following the approach described in the previous recipe, define a method that takes a function as a parameter. Specify the function signature you expect to receive, and then execute that function inside the body of the method.
The following example defines a method named exec
that takes a function as an input
parameter. That function must take one Int
as an input parameter and return
nothing:
def
exec
(
callback
:
Int
=>
Unit
)
{
// invoke the function we were given, giving it an Int parameter
callback
(
1
)
}
Next, define a function that matches the expected signature. The
following plusOne
function matches
that signature, because it takes an Int
argument and returns nothing:
val
plusOne
=
(
i
:
Int
)
=>
{
println
(
i
+
1
)
}
Now you can pass plusOne
into
the exec
function:
exec
(
plusOne
)
Because the function is called inside the method, this prints the
number 2
.
Any function that matches this signature can be passed into the
exec
method. To demonstrate this,
define a new function named plusTen
that also takes an Int
and returns
nothing:
val
plusTen
=
(
i
:
Int
)
=>
{
println
(
i
+
10
)
}
Now you can pass it into your exec
function, and see that it also
works:
exec
(
plusTen
)
// prints 11
Although these examples are simple, you can see the power of the technique: you can easily swap in interchangeable algorithms. As long as ...
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.