As a Java developer, you may have felt the lack of closures as a horrible pain. Fortunately, Java’s 8th version introduced lambda functions, which is great news for coders; however, in Android development, we are still forced to use Java 7.

Guess what? The waiting is over. Our fellow Esko Luontola has found a workaround for using lambda expressions when coding Android apps! How does it work? Well, according to his Readme:

Just as there was Retroweaver et al. for running Java 5 code with generics on Java 1.4, Retrolambda lets you run Java 8 code with lambda expressions and method references on Java 7 or lower. It does this by transforming your Java 8 compiled bytecode so that it can run on a Java 7 runtime.

In this post, I will show you how to set up this fantastic tool, in only two easy steps, using Android Studio and Gradle.

Install JAVA 8 SDK

Firstly, you need to set up the JAVA 8 JDK on your machine. Download the appropriate version for yours.

Once done (downloaded and installed), open Android Studio. Navigate to File > Project structure. There, change the JDK location to the path where you have freshly installed Java 8. For my part, using a Mac (Yosemite 10.10.2), it is:

/Library/Java/JavaVirtualMachines/jdk1.8.0_31.jdk/Contents/Home

Using a Linux machine, it should be:

/usr/lib/jvm/java-8-oracle

Finally, using Windows:

C:\Program Files\Java\jdk1.8.0_31.jdk\

In nonstandard installations, it’s the java folder that contains the bin folder.

undefined
Figure: Change SDK location in AndroidStudio

Set up Gradle

Nice! You’re almost done with configuration. The last step is to edit Gradle’s configuration. We are going to use the Retrolambda plugin from Evan Tatarka, for allowing lambda expression support.

First, open build.gradle from your application. Change the compileOptions node (nested in android one) to the following:

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

Then, at the bottom of the same file, append this code:

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'me.tatarka:gradle-retrolambda:2.5.0'
    }
}

repositories {
    mavenCentral()
}

apply plugin: 'me.tatarka.retrolambda'

That’s all folks! Try to build your project, everything should be fine.

Release the lambdas!

Now you can remove your ugly anonymous inner classes and replace with elegant lambdas like this:

myButton.setOnClickListener((button) -> {
    this.hasBeenClicked = true;
    super.saveForm();
});

Keep in mind Retrolambda only allows lambda expression support. Other features from Java 8 are not available for Android development.