Week 54 — What is a functional interface?

Question of the Week #54
What is a functional interface?
9 Replies
Eric McIntyre
Eric McIntyre11mo ago
In some cases, it is useful to pass code to a method. This is possible using inheritance. An interface can with a single (abstract) method contains the passed code and a method can then accept objects of that interface. When calling that method, it is possible to provide concrete objects containing the implementation which should be passed to the method.
//this interface contains code which is supplied to a method
interface SomethingWeCanRun {
void run();
}
//this interface contains code which is supplied to a method
interface SomethingWeCanRun {
void run();
}
//here is a method accepting implementations of that interface
void runFromInterface(SomethingWeCanRun impl){
impl.run();
}
//here is a method accepting implementations of that interface
void runFromInterface(SomethingWeCanRun impl){
impl.run();
}
//we can call that method and pass code using an implementation of that interface
SomethingWeCanRun impl = new SomethingWeCanRun(){
//this example uses an anonymous class
@Override
public void run(){
System.out.println("Hi");
}
};
//now pass the code
runFromInterface(impl);//prints Hi
//we can call that method and pass code using an implementation of that interface
SomethingWeCanRun impl = new SomethingWeCanRun(){
//this example uses an anonymous class
@Override
public void run(){
System.out.println("Hi");
}
};
//now pass the code
runFromInterface(impl);//prints Hi
Eric McIntyre
Eric McIntyre11mo ago
Java 8 introduced Lambda expressions which are a way to simplify the above pattern by not needing to write out the declaration of the anonymous class. It provides a shorthand for creating an instance of an interface with a single (abstract) method. This is done by first listing the arguments inside parenthesis followed by an arrow (->) and a block of code surrounded with curly brackets:
SomethingWeCanRun impl = () -> {
System.out.println("Hi");
};
runFromInterface(impl);//prints Hi
SomethingWeCanRun impl = () -> {
System.out.println("Hi");
};
runFromInterface(impl);//prints Hi
Since this is only possible with interfaces with a single (abstract) method, there is an annotation @FunctionalInterface which checks that an interface actually only consists of a single (abstract) method. Adding this to an interface with multiple non-default methods or no non-default method results in a compile-time error:
@FunctionalInterface
interface validFunctionalInterface{
void someMethod();
}
@FunctionalInterface
interface validFunctionalInterfaceWithDefaultMethod{
void someMethod();
default void someDefaultMethod(){//additional default methods are allowed
someMethod();
}
}
//@FunctionalInterface//compile-time-error
interface InterfaceWithTooManyMethods{
void someMethod();
void otherMethod();
}
//@FunctionalInterface//compile-time-error
interface InterfaceWithNoMethod{
}
@FunctionalInterface
interface validFunctionalInterface{
void someMethod();
}
@FunctionalInterface
interface validFunctionalInterfaceWithDefaultMethod{
void someMethod();
default void someDefaultMethod(){//additional default methods are allowed
someMethod();
}
}
//@FunctionalInterface//compile-time-error
interface InterfaceWithTooManyMethods{
void someMethod();
void otherMethod();
}
//@FunctionalInterface//compile-time-error
interface InterfaceWithNoMethod{
}
📖 Sample answer from dan1st
Eric McIntyre
Eric McIntyre11mo ago
A functional interface is an interface that has only one abstract method. They were introduced in Java 8 to facilitate the use of lambda expressions for functional programming.
Submission from ig.imanish
Eric McIntyre
Eric McIntyre11mo ago
A functional interface is an interface that only defines a specific function. So it's not about how that function is performed, but only about what the function does. A simple example of a functional interface is a switch. A switch has two functions: on and off. It doesn't matter how the switch is made as long as it can perform these two functions. In java we have so much functional interfaces such as Predicate<T> it is a functional interface in Java. It defines a single function, test(). This function takes an object of type T as an argument and returns a boolean value.
Submission from ibraa6305
Eric McIntyre
Eric McIntyre11mo ago
A functional interface is an interface that only declares one abstract method. They can optionally annoted with @FunctionalInterface as well, for additional compiler warnings or suggestions. A functional interface is useful because it allows you to use a syntax sugar known as a lambda expression. A lambda allows you to anonymously instantiate a class that implements the functional interface, and quickly declare a body for the single implementing method. Functional interfaces are useful because they effectively allow you to use store functions inside variables, pass them around, define them quickly in method arguments, etc, allowing for the use of functional programming paradigms in Java. They are usually created for the purpose of defining an action that should be taken given a set of arguments. The most commonly used functional interfaces are Consumer<>, which takes in an argument and returns nothing, a Function<>, which takes an argument and returns a value, a Runnable<>, which takes in nothing and returns nothing, a Predicate<> that takes arguments and returns a boolean value, and a Supplier<>, which takes no arguments and returns a value.
Submission from arkosammy12
Eric McIntyre
Eric McIntyre11mo ago
A functional interface is an interface that contains only one abstract method
Submission from neverasktwice
Eric McIntyre
Eric McIntyre11mo ago
By literal definition, a functional interface is an interface that declares exactly one abstract method. Not zero, not more than one. By abstract method we mean a method that is declared, but not given a definition. Not a default method, not a static method, not a private instance method. Just the classic method signature that implementing classes will have to implement. This is an example of a functional interface:
@FunctionalInterface
public interface Thing {
void doStuff();
}
@FunctionalInterface
public interface Thing {
void doStuff();
}
By the above definition, comes that what counts with a functional interface, is the one method that needs to be implemented by its implementors. If and when a functional interface comes with other things, like default and static methods, those are mostly fine-to-ignore-for-now helpers that were best put inside that functional interface declaration rather than creating yet another place to put them in. What matters in a functional interface, is its one abstract method. As the name suggests, functional interfaces intervene when using a functional style of programming. As what matters in a functional interface is the method it needs to implement, then what matters with an object that can be given where a functional interface is wanted, is how it implements the method. So, the object is little more than just a method. Java doesn't directly define a type system where methods can be stored and passed in variables, and functional interfaces is the closest replacement for that. A typical example for functional programming is sorting a list, providing a method that tells how to sort two items with regard to each other.
List<String> byFirstLetter = new ArrayList(List.of("Beth", "Alphonse", "Albert"));
byFirstLetter.sort((a, b) -> Character.compare(a.charAt(0), b.charAt(0)));
List<String> byFirstLetter = new ArrayList(List.of("Beth", "Alphonse", "Albert"));
byFirstLetter.sort((a, b) -> Character.compare(a.charAt(0), b.charAt(0)));
Here the sort() method in List, takes as parameter a Comparator<String>. Comparator is a functional interface: exactly one abstract method, that tells how two items compare with each other.
⭐ Submission from kyo_chan42
Eric McIntyre
Eric McIntyre11mo ago
Functional interfaces are a feature of Java 8 and later versions. Java is an object-oriented programming language, and it uses classes and objects. To make functional programming possible, we can use functional interfaces, thanks to functional interfaces we can use lambda expressions and method references. Functional interface contains only one abstract method and it also can contain default and static methods. We can use @FunctionalInterface annotation to force java compiler to check if a functional interface satisfy the requirements of a functional interface. Code example: @FunctionalInterface interface FuncInterface<T, R> { R apply(T value); static void staticMethod() {} default void defaultMethod() {} } To implement functional interface we can use anonymous class, lambda expression and method reference. Compiler automatically creates hidden class that implements interface FuncInterface<T, R> for lambda expression and method reference. Code examples, respectively:
FuncInterface<Integer, Integer> square = new FuncInterface<Integer, Integer>() { @Override public Integer apply(Integer value) { return value * value; } };
FuncInterface<Integer, Integer> square = value -> value * value;
class Functions { public static int square(int value) { return value * value; } } FuncInterface<Integer, Integer> square = Functions::square;
⭐ Submission from ibrohimsobirov
Eric McIntyre
Eric McIntyre11mo ago
Functional interfaces in Java are interfaces with the @FunctionalInterface annotation. This annotation requires the interface to have only one non-static abstract method. Once you have a functional interface you can use lambda syntax as opposed to an anonymous inner class. Lambda expressions are composed of a parameter list, an arrow syntax (->), and a function body or simply the returned value. A lambda expression is an instance of the functional interface and thus can be used as a value. Here is an example of a functional interface instance of Runnable, being passed in as an argument to the start method of the Thread class. :
//...
Thread.ofPlatform()
.start(new Runnable() {
@Override
public void run() {

System.out.println("Hello World");
}
}).join();

// Notice how lambda syntax has simplified our code's readability

Thread.ofPlatform()
.start(() -> {

System.out.println("Hello World");
}).join();
//...
//...
Thread.ofPlatform()
.start(new Runnable() {
@Override
public void run() {

System.out.println("Hello World");
}
}).join();

// Notice how lambda syntax has simplified our code's readability

Thread.ofPlatform()
.start(() -> {

System.out.println("Hello World");
}).join();
//...
There are different use-cases for functional interfaces, but they are apparent in the Streams API.
//...
int evenNumbersSum = Stream.iterate(0, (Integer n) -> n + 1) // parathesis are only needed if you have more than one variable, or you define it's type.
.mapToInt(obj -> (int) obj)
.limit(100)
.filter((n) -> { return n % 2 == 0; } ) // add a block if you want to have multiple lines, just make sure your have a return statement.
.sum();
System.out.println(STR."The total number of even numbers from 1-100 is \{ evenNumbersSum }");
//...
//...
int evenNumbersSum = Stream.iterate(0, (Integer n) -> n + 1) // parathesis are only needed if you have more than one variable, or you define it's type.
.mapToInt(obj -> (int) obj)
.limit(100)
.filter((n) -> { return n % 2 == 0; } ) // add a block if you want to have multiple lines, just make sure your have a return statement.
.sum();
System.out.println(STR."The total number of even numbers from 1-100 is \{ evenNumbersSum }");
//...
In this example, mapToInt takes in a functional interface (IntFunction) which has a method that performs a mapping operation on a value with a garenteed return type of int
⭐ Submission from karter907
Want results from more Discord servers?
Add your server