9.3. Defining a Method That Accepts a Simple Function Parameter
Problem
You want to create a method that takes a simple function as a method parameter.
Solution
This solution follows a three-step process:
Define your method, including the signature for the function you want to take as a method parameter.
Define one or more functions that match this signature.
Sometime later, pass the function(s) as a parameter to your method.
To demonstrate this, define a method named executeFunction, which takes a function as a
parameter. The method will take one parameter named callback, which is a function. That function
must have no input parameters and must return nothing:
defexecuteFunction(callback:()=>Unit){callback()}
Two quick notes:
The
callback:()syntax defines a function that has no parameters. If the function had parameters, the types would be listed inside the parentheses.The
=> Unitportion of the code indicates that this method returns nothing.
I’ll discuss this syntax more shortly.
Next, define a function that matches this signature. The following
function named sayHello takes no
input parameters and returns nothing:
valsayHello=()=>{println("Hello")}
In the last step of the recipe, pass the sayHello function to the executeFunction method:
executeFunction(sayHello)
The REPL demonstrates how this works:
scala>def executeFunction(callback:() => Unit) { callback() }executeFunction: (callback: () => Unit)Unit scala>val sayHello = () => { println("Hello") }sayHello: () => Unit = <function0> ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access