TIL: Lambda Expressions

Posted by in Software

TL;DR: A lambda expression is a shortcut notation to anonymous inner classes containing a single method. Usually, they define implementations for functional interfaces (interfaces declaring a single method).

Today I finally found out what lambda expressions are (formally) by watching this tutorial.

Lambda expressions are a concise way of passing pieces of code around. You can look at lambda expressions as shorthand for anonymous inner classes.

There is a catch though: They are valid for functional interfaces.

Functional interfaces

Functional interfaces are interfaces defining a single method, like this:

Following interface is not functional, hence it can’t be used in lambdas:


Anonymous inner classes are inline implementations of e.g. interfaces. I.e. instead of defining a full object, creating and using it, you do it on the fly. If it just implements a functional interface, you can use lambda expression. Here’s an example:

Assuming you have the interface:

and a class:

We want to define some code for the Operation and execute() it:

Now, we can define the Operation via anonymous inner class:

It will print 30 , which is 20 + 10.

We can also use lambda expressions (remember the functional interface thing?):

The result will be the same. Much shorter, no?

We can go even further (since the interface is not ambiguous) and remove the types:

TADA! Now you can see it fits with the anti-boilerplate trend in android development.


A little experiment: If you find this post and ad below useful, please check the ad out 🙂