Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda expressions in android

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?

like image 698
user3430722 Avatar asked Jun 13 '14 18:06

user3430722


People also ask

What is a lambda expression example?

Lambda expressions basically express instances of functional interfaces (An interface with single abstract method is called functional interface. An example is java.lang.Runnable).

What is lambda expression?

A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.

What are lambda expressions in Kotlin?

Lambda expression is a simplified representation of a function. It can be passed as a parameter, stored in a variable or even returned as a value. Note: If you are new to Android app development or just getting started, you should get a head start from Kotlin for Android: An Introduction.

What is the benefit of lambda expressions in Kotlin?

Lambdas are one of the most powerful tools in Kotlin, and in any other modern language, since it allows modelling functions in a much simpler way. The only way we can do this in Java 6 is by declaring interfaces with a single method, and creating anonymous objects that implement those interfaces.


1 Answers

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

like image 97
Pieces Avatar answered Sep 23 '22 19:09

Pieces