Android N Lambda and Method Reference

Introduction

In this tutorial I am going to show how to use Java 8 Lambdas and Method References in Android.
Lambdas and Method References simplify development by removing boilerplate code related to implementing Anonymous classes making the code easier to write and to maintain.
First I will Show how to use them in Java. Then I will present a practical usage example with Anroid.
For source code and references check the last section .
Lets dive in and see how to use them with Anroid N.

Tools You Need?

For this tutorial you need to have
Android N SDK platform (API 24). You can download it using the Android SDK Manager.
Android Studio 2.1 or greater

Functional Interface

To use lambdas and method references you need to understand the meaning of functional interface. Introduced in Java 8 functional interfaces are interfaces that contain ONE method. There are some exceptions but basically this is what you need to understand to get started.

Lambdas and Method Reference

In order to use Lambdas and method reference you need to have a method or a constructor that takes as an argument a functional interface. Instead of providing an object implementing the method you can inline it using lambdas or pass in the method to be used directly. (The methods parameters must match those of the functional interface)

Example

Let’s say we have this functional interface.

public interface Speech {
    void speak(String text);
}

And we have a Class that have a Speech field passed using the constructor.

public class Speaker {
    private Speech speech;

    public Speaker(Speech speech) {
        this.speech = speech;
    }

    public void talk() {
        speech.speak(" speech");
    }
}

One way we can hook this together is to create a new instance of speech and hook it to the speaker.

        Speaker speaker = new Speaker(new Speech() {
            public void speak(String speech) {
                System.out.println("Old way " + speech);
            }
        });
        speaker.talk();

To use Lambdas we use the -> operator. The example becomes

        Speaker speaker = new Speaker((speech) -> {
            System.out.println("Lambda " + speech);
        });
        speaker.talk();

Using lambdas made the code easier to read and understand and got rid of a lot of boilerplate code.
To use method reference we use :: to pass the method to use. object::methodname

// The current object must have this method
Speaker speaker = new Speaker(this::speak);
Public void speak(String text){
    System.out.println("Method reference " + text);
}

Getting Lambda And Method Reference to work in Android N

To enable Lambda and Method Reference in Android N preview you need to set the version to N and enable the Jack compiler a new compiler for Android. In your application’s gradle build file .
So inside your build file you should add jackOptions and enable the Jack compiler.


        minSdkVersion 24
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        jackOptions {
            enabled true
        }

Usage Example

One usage of lambdas is to provide implementation OnClickListener for the setOnClickListener method of a graphical element.
Start by creating a new project with a MainActivity and setup the build file as shown above.
Add a button to the activity_main.xml

<Button
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="@string/lambda"
  android:id="@+id/lambda_button"
 />

Grab a reference to this button inside your MainActivity.java

Button lambdaButton = (Button) findViewById(R.id.lambda_button);

Use Lambda to provide the implementation for the
setOnClickListener. We are going to show a toast.

lambdaButton.setOnClickListener((v) -> {
 String toastText = "I Love Lambdas";
Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();
       }
);

Run your application And you get something like this.

Source Code

Lambda And Method Reference Source Code

Android Application Source Code

References

Functional Interface

Herbert Schildt, Java: The Complete Reference, Ninth Edition ISBN:978-0071808552

Android Use Java 8 Language Features