Void function as argument in Java and Scala

Simple example shows how to pass a function to a method. The function doesn’t have argument and doesn’t return a result.

Let say we have a method with name f1. The method has one argument – a function without arguments and without result.

The following are examples on Java and on Scala.

Java:

// Define a method with a function without arguments as parameter
private void f1(Runnable f) {
 ...
 f.run();
 ...
 }
...

// Call the f1 method with lambda function
f1(() -> {
 int i = 123;
 System.out.printf("i = %d\n", i);
 });

Scala:

 // Define a method with a function without arguments as parameter
 def f1(f: () => Unit): Unit = {
    ...
    f()
    ...
 }
 ...
// Call the f1 method with lambda function
 f1(() => {
     val i = 123
     println(s"i = $i"))
   })

See more on GitHub

Advertisements

About ysden123

We are not only for work... All my time free from work I spend on photography. Most photos are from our travels. I like make photos in still life style as well.
This entry was posted in java, Programming, Scala and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s