Retrolambda on Android

Using Java 8 goodies on java 6/7

César Ferreira
AndroidPub

--

After Party tricks with RxJava, RxAndroid and Retrolambda, a lot of you folks reached out on an easy and fast way to setup Retrolambda on an android project.

4 easy steps

  1. Download and install jdk8.
  2. Add the following to your project’s main build.gradle
buildscript {
repositories {
mavenCentral()
}

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

3. Now add this to your application module’s build.gradle

apply plugin: 'com.android.application' // or apply plugin: 'java'
apply plugin: 'me.tatarka.retrolambda'

4. Add these lines to your application module’s build.gradle to inform the IDE of the language level:

android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}

You can now start writing shorter code…

So things like this:

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
log("Clicked");
}
});

Become this:

button.setOnClickListener(v -> log("Clicked"));

A few Tips

Build fails when using android-apt

This is because android-apt modifies gradle’s javaCompile task and this plugin replaces it. Since v2.4.1 this is fixed, you just need to ensure you apply retrolambda last.

Example:

apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'
apply plugin: 'me.tatarka.retrolambda' // I'm the last one!

Generated code is incompatible with Retrolambda

The conversion can fail if a library contains bytecode that is incompatible with retrolambda (pretty rare). See orfjackal/retrolambda#25 for more information.

If you add this to your application module’s build.gradle you should be fine:

retrolambda {
jvmArgs '-noverify'
}

(I personally add this to all my projects as a precaution)

Hit me up on @cesarmcferreira if you have any questions ☺

--

--