I implemented the functional interface, using the functional method in a lambda function. Everything works fine except I get an error that this inherited abstract method (in my case, the functional method) must be implemented. And here I'm confused. I used the lambda function to implement this functional method. Why should I again implement the method? How is the implementation of functional methods done correctly?
Here is my code:
interface MyFunction {
int getValue(int num);
}
class Factorial implements MyFunction {
public static void main (String [] args) {
MyFunction myFactorialFunc = (num) -> {
int fact = 1;
for(int i = 1; i <= num; i++){
fact = i * fact;
}
return fact;
};
System.out.println(myFactorialFunc.getValue(7));
}
}
I guess you must have heard from somewhere that "you can implement single-method interfaces with a lambda expression!" and proceeded to try it out by writing this code, all the while misunderstanding what is meant by that.
Lambda expressions doesn't actually allow you to write class MyClass implements SomeInterface
without declaring the required method. As far as the compiler is concerned, Factorial
only has a main
method declared, and no getValue
method, so it doesn't implement the MyFunction
interface.
Your code does demonstrate "you can implement single-method interfaces with a lambda expression" though. Here in the main
method, you assigned a lambda expression to a variable of type MyFunction
:
MyFunction myFactorialFunc = (num) -> {
int fact = 1;
for(int i = 1; i <= num; i++){
fact = i * fact;
}
return fact;
};
Normally, you have to put an implementation of MyFunction
on the right-hand side of =
, don't you? But now, you can just use a lambda expression! This is because the signature of the lambda expression matches the signature of the single method in the interface, so the compiler goes "yeah, that's fine, I'll just use this as the implementation of that method".