Using Lambda Expressions in Android

In this tutorial we will learn how to use Lambda Expressions in Android.

As you know Android support till JDK 7. It dose not support JDK 8. That's why we can't use Lambda Expression directly while programming any Android application.


So, Firstly let we discuss about what are the Advantages of Lambda Expression and why we use them?

1. Fewer lines of code

One of the benefits of using lambda expression is the reduced amount of code.

For Example:

a.
Button lamdaTest = (Button) findViewById(R.id.button);

lamdaTest.setOnClickListener(new View.OnClickListener() {
    @Override    public void onClick(View v) {
        // Some Action    }
});

Above code can be written as:

Button lamdaTest = (Button) findViewById(R.id.button);

lamdaTest.setOnClickListener(v -> {
    //some action}); }

b.
runOnUiThread(new Runnable() {
    @Override    public void run() {
        Log.i("Result:", "Hello");
    }
});

Above code can be written as:

runOnUiThread(() -> Log.i("Result:", "Hello"));
c. 
new Thread(new Runnable() {
    @Override    public void run() {
        Log.i("Result:", "Hello");
    }
}).start();

Above code can be written as:

new Thread(()-> Log.i("Result:", "Hello")).start();

2. You can now add default and static methods to interfaces that provide concrete implementations.

Now, we will learn how to use Lambda Expressions in Android. So, to use Lambda Expression we have to use Library named Retrolambda. 

Open build.gradle file and add dependency:

classpath 'me.tatarka:gradle-retrolambda:3.2.2'

Your build.gradle will look like:
So, Give a try to retrolambda library and enjoy cool features of Lambda Expression in android.

Click here to download Demo Project



Comments

Popular posts from this blog

Android Sudoku Game Project With Source Code