Java … FunctionalInterface … WTF?

Posted by & filed under , .

java codeIf you’ve been doing “stuff” with Java 8 for a while I’m sure you’ve stepped into lambdas territory and the joys of succinct code it allows to be written.

And if you are like me you probably found yourself using lambda’s everywhere you are confronted with a single-method interface. Which is allowed. In fact it’s what lambdas are all about, right?

So then, if you are like me, you too get curious when you see something called FunctionalInterface in the JDK. And you wonder “hmmm what would that be for”?

So I open the JavaDoc (see here with your own eyes:

An informative annotation type used to indicate that an interface type declaration is intended to be a functional interface as defined by the Java Language Specification. Conceptually, a functional interface has exactly one abstract method.

Ok that makes sense. But wait… I’ve written tons of interfaces in Java with a single method and then ended up applying lambda’s everywhere for it. How is that possible??? And the JavaDoc has the answer again — right at the end:

However, the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration.

So let me get this straight (my theatre writing is still work in progress so please bear with me):

Oracle: We’re giving you this lambda feature in the language, but if you want to use it, you need to annotate all the interfaces you want to use it with with @FunctionalInterface

Java Community: OK… what about the interfaces we don’t annotate them with @FunctionalInterface?

Oracle: Oh yeah, you can use those too!

End of play! 😀

Oh and it turns out that all of the interfaces in the JDK which should be functional are actually annotated with @FunctionalInterface… even though it actually doesn’t make a difference according to their own selves.

It reminds me of that quote from “Father Ted” TV series when Ted and Dougal are describing Father Jack: “He was terrible with strangers … and people he knew” 🙂