Translate

Search This Blog

Wednesday 13 June 2018

Java8 - Functional interfaces

Functional interfaces
Java8 has added to it's kitty another concept know as functional interfaces.

So what exactly is an functional interfaces?

  • Functional interfaces are interfaces with exactly a single abstract method (SAM). 
  • It is represented by the annotation type @FunctionalInterface. 
    • This annotation let's the compiler know that the interfaces should adhere to the contract of SAM.

NOTE:

  • A couple of things here that this interface can also have other default functions but not another abstract method. 
  • These interfaces can also be extended by another interfaces and can be called functional interface as long it does not have another abstract method.
  • Also compiler will treat all SAM interfaces as functional regardless if the annotation is present or not.


So how do we use this interfaces?
These interfaces can be represented using

  • Lamda expressions 
  • Method reference and 
  • Constructor reference.(Lamda expressions another important concept I have covered in another blog article)


Examples of functional interfaces
in Java8 are Runnable, Comparator, ActionListener, Callable etc.



Tuesday 5 June 2018

Java8 - Lamda functions

Java8 - Lamda expressions

What are Lamda expressions?
Lamda expressions is Java's introduction to functional programming.  Lamda expressions can be created and passed around like regular objects and executed when needed.

Why do we have Lamda expressions?
Java is often criticised as verbose, with Lamda expressions there is an attempt to decrease this verbosity. They address the bulkiness of the anonymous inner classes.

With lamda expression you can now represent single method interfaces in a simple and concise way. These single method interfaces are often termed as functional interfaces as in Java8. If you do not know about functional interfaces check my other post on the same.

So how do we create these Lamda expression?
Lamda expressions are composed of 3 parts:
1. Argument list
     It is represented like any other method definition like for example () or (int x, int y) etc
2. Arrow token
    Represented by the -> symbol
3. Body
    If the body consists of a single line then curlies are not required.

Example of such an expression is 

Runnable r = () -> System.out.println("I am running"); 

It is worth noting that the expressions find their usage in places where there are interfaces with single abstract method. This way, the compiler knows how to exactly match the argument list and the method to the definition in the interface. 

If you understand this article it will form the basis for the next article where we will dive into the intricacies of lamda expression