7

How use lambda expressions in android? For example, I compile this code in IntelliJ IDEA:

package com.example.myapp;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;

public class MyActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        test s = () -> {return "Lambda expressions test";};
        AlertDialog alertDialog = new AlertDialog.Builder(this)
                .setTitle("Lambda expression")
                .setMessage(s.t())
                .create();
        alertDialog.show();
    }
}
interface test {
    public String t();
}

But have this erorrs:

Information:Using javac 1.8.0_05 to compile java sources
Information:36 errors
Information:0 warnings
Information:Compilation completed with 36 errors and 0 warnings in 29 sec
Error:Android Dex: [myappі] UNEXPECTED TOP-LEVEL EXCEPTION:
Error:Android Dex: [myappі] com.android.dx.cf.iface.ParseException: InvokeDynamic not supported 

How to set up so you can use lambda expressions?

user3430722
  • 345
  • 1
  • 5
  • 12

3 Answers3

7

Android only supports java 6 and 7. You can use plugins to get lambdas though such as https://github.com/evant/gradle-retrolambda.

Pieces
  • 2,256
  • 5
  • 25
  • 39
3

In your build.gradle add this:

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

Assuming you installed Java 8 on your machine!

Also, add this:

dependencies {
    classpath 'com.android.tools.build:gradle:1.0.0'
    classpath 'me.tatarka:gradle-retrolambda:2.5.0'
}

And finally:

apply plugin: 'me.tatarka.retrolambda'
IgorGanapolsky
  • 26,189
  • 23
  • 116
  • 147
1

Java 8 language features are now supported by the Android build system

Yesterday, we released Android Studio 2.4 Preview 6. Java 8 language features are now supported by the Android build system in the javac/dx compilation path. Android Studio's Gradle plugin now desugars Java 8 class files to Java 7-compatible class files, so you can use lambdas, method references and other features of Java 8.

Source : https://android-developers.googleblog.com/2017/04/java-8-language-features-support-update.html

Edit: 06/01/2017

Lambda Expressions now supported in Android Studio 3.0

Oussaki
  • 1,449
  • 2
  • 21
  • 30