-4
@FunctionalInterface
public interface myFunction<T> {
  abstract double apply(T t);
}

The above code is my functional interface.

And the following code is my lambda expression. What does functional interface do in my lambda expression as there is only a simple 'double'? If there is no functional interface, what will there be like?

import java.util.HashSet;

public class TestFindArea {
public static double findArea(myFunction<Double> f,double a,double b){
    return (f.apply(a)+f.apply(b))*(b-a)/2;
}
    public static void main(String[] args) {
        System.out.println(findArea((x) -> x+2 , 4, 8) );
6
  • Are you asking what the @FunctionalInterface annotation is for? Or are you asking to explain your code? I can't understand what you're asking. Also, please respect the Java naming conventions. Classes and interfaces star with an uppercase letter. Commented Nov 25, 2017 at 10:03
  • I don't understand why in functional programming there have to be a functional interface and what does the interface do。 Commented Nov 25, 2017 at 10:04
  • In functional programming, there doesn't have to be functional interfaces. The basic principle is to pass funtions to other functions. But Java is an OO language, and doesn't have direct support for functions. It has support for interfaces though. So, the Java designers chose to use an interface with a single method to represent a function type. And lamda expressions are instances of those functional interfaces. Other functional languages, such as JavaScript or Kotlin, don't need such interfaces. They can just define top-level functions and pass them directly. Is that what you're asking? Commented Nov 25, 2017 at 10:07
  • Lamda can only be used with functional interface Commented Nov 25, 2017 at 10:09
  • 1
    Downvoted for lack of prior research. Commented Nov 25, 2017 at 10:12

1 Answer 1

0

What does functional interface do in my lambda expression as there is only a simple 'double'?

your functional interface represents a function that takes a generic type T and returns a double, meaning wherever we utilize the functional interface as the target type, eventually, we will need to assign or pass it a function which satisfies the function descriptor of its SAM. Thus, in your case, the first argument to findArea((x) -> x+2 , 4, 8) is the function being passed to the findArea method and can be read as "given a number of type Double, add the number 2 to it and return the result".

If there is no functional interface, what will there be like?

Then you cannot pass functions as arguments to other functions nor can you use functions as return types for other functions and nor can you assign a lambda expression to an interface.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.