• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Java 8 Functional Interfaces

 
Ranch Hand
Posts: 10198
3
Mac PPC Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In the recent days, I have been working extensively with Scala and I was eagerly looking forward using Java again and Java 8 seems to be promising with a lot of new features. I heard a lot about functional interfaces in Java 8, but never had the time to get into it. What exactly is it? Is it the interface that we write and tell to the compiler through annotations to treat them differently than the traditional interfaces in Java? I would be interested to know more.
 
Saloon Keeper
Posts: 15510
363
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A functional interface is an interface that has only one method. Methods that take the interface as their parameter can then be passed a lambda instead of an object reference.

The @FunctionalInterface annotation is comparable to the @Override annotation. It explains to the compiler what you're trying to do, and the compiler will help you by making sure what you're trying to do is what happens.

If you don't use the @Override annotation, the compiler will not complain if you accidentally end up writing a method that doesn't override the one declared in the super-type. This can lead to problems.

With @FunctionalInterface, you tell the compiler that the interface you're writing should be able to have lambda "instances", instead of traditional anonymous instances. If you accidentally add a second method to the interface, the compiler will complain.

A functional interface will still be a functional interface without the annotation.

For instance, Comparator is now a functional interface. Instead of doing this:
You can now do this:
Actually it's even better to do this:
 
reply
    Bookmark Topic Watch Topic
  • New Topic