1.3 Function-Type interface

Source: Internet
Author: User

1.3 Function-Type interface

As we discussed, there are many existing interfaces in Java that require encapsulating code blocks, such as runnable or comparator. Lambda expressions are backwards-compatible with these interfaces.

For an interface that contains only an abstract method, you can create an object of that interface through a lambda expression. Such an interface is called a functional interface.

Note: You may wonder why the functional interface must have only one abstract method. Are the methods in the interface not all abstract? In fact, interfaces often re-declare methods in the object class, such as ToString or clone, and these methods are declared as not abstract. (Some interfaces in the Java API re-declares the method of the object class in order to correlate Javadoc annotations.) For specific examples, refer to the comparator API. You will see in section 1.7 that the more important point is that the interface in Java 8 can declare a non-abstract method.

To demonstrate functional interface transformations, we take the Arrays.sort method as an example. The second parameter of the method requires an instance of the comparator interface (which contains only one method). Next we write a simple lambda expression:

  1. arrays.sort (words,  
  2. (First, second)  - >  integer.compare (First.length (),  second.length ()));  

Behind this expression, the Arrays.sort method receives an instance of the class that implements the Comparator<string> interface. Calling the object's compare method executes the code in the lambda expression. The management of these objects and classes relies entirely on how they are implemented, and is therefore more efficient than traditional internal classes. You'd better think of a lambda expression as a function, not an object, and remember that it can be converted to a functional interface.

This conversion to the interface makes the lambda expression very compelling, and its syntax is so streamlined. Here's another example:

  1. button.setonaction (event - > &NBSP;
  2. System.out.println ("Thanks for clicking!"));

It's obviously more readable than the inner class.

In fact, the conversion of a functional interface is the only thing you can do with a lambda expression in Java. In other programming languages that support function text, you can declare function types such as (string, string) and int, declare variables of this type, and use these variables to hold function expressions. However, Java designers have decided to stick to familiar interface concepts instead of adding function types to java.

Note: You cannot even assign a lambda expression to a variable of type object because object is not a functional interface.

The Java API defines a number of very general functional interfaces in the Java.util.function package (we will explain these interfaces in detail in chapters 2nd and 3rd). The interface bifunction<t,u,r> describes the method parameters of the T and U types and the return type R. You can save our string comparison lambda expression in a variable of that type.

  1. bifunction < string , String,  integer > &NBSP; comp &NBSP;
  2. = (first, second)- > Integer.compare (First.length (), second.length ());

However, this is not helpful for sorting. There is no Arrays.sort method to receive bifunction as a parameter. If you've used other functional programming languages before, you might be surprised.

But for Java developers, this is no more natural. Interfaces like comparator have a specific purpose, not just a method of receiving parameters and return types. Java 8 retains this habit. When you want to use a lambda expression, you still have to remember the purpose of the expression and assign it a functional interface.

Now the Java 8 API uses the interfaces in the java.util.function, which are likely to be used everywhere in the future. Keep in mind, however, that any lambda expression can be converted to the corresponding functional interface in the API that is currently in use.

Note: You can annotate @functionalinterface annotations on any functional interface, which has two benefits. First, the compiler checks the entity that labels the annotation and checks to see if it is an interface that contains only an abstract method. In addition, the Javadoc page also contains a declaration stating that the interface is a function-type interface.

This annotation does not require mandatory use. Conceptually, all interfaces that contain only one abstract method are functional interfaces, but using @functionalinterface annotations will make your code look clearer.

Finally, when a lambda expression is converted to an instance of a functional interface, be aware of handling check-period exceptions. If a check-period exception may be thrown in a lambda expression, the exception needs to be declared in the abstract method of the target interface. For example, the following expression produces an error:

  1. RUNNABLE&NBSP; sleeper  =  ()  - >  {  System.out.println ("Zzz");  thread.sleep (+); };  
  2. Error: Thread.Sleep can throw a check period of interruptedexception.

Since Runnable.run cannot throw any exceptions, this assignment is not legal and there are two ways to fix the problem. One is to catch an exception in a lambda expression, and the other is to assign a lambda expression to an interface whose abstract method can throw an exception. For example, the call method of the callable interface can throw any exception, so you can assign the lambda expression to callable<void> (if you add a "return NULL" statement).

1.3 Function-Type interface

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.