Java 8 vs. Scala Lambda expressions, scalalamloud

Source: Internet
Author: User

Java 8 vs. Scala Lambda expressions, scalalamloud

Hussachai Puripunpinyo considers Java as a static strong-type language. Therefore, although Java 8 has become a first-class citizen, it can be passed as a function parameter or return value, but it must have a type, that is, the interface, and the Lambda expression is the object that implements the Functional interface. Although developers do not need to worry about creating function objects, the compiler will do these tasks, but Java is not as good as Scala's type inference mechanism, to declare a Lambda expression in Java, you must specify the target type. Considering that Java must maintain backward compatibility, this is acceptable and understandable. In fact, Java has already done well in terms of compatibility, such as Thread. stop () already exists in JDK 1.0. Although it has been marked as "obsolete" for decades, it still exists, therefore, you should not expect Java to change its syntax quickly because other languages have better syntax.

To support Lambda expressions, Java introduces a functional interface, which has only one abstract method. @ FunctionalInterface is an annotation used to indicate that the annotated interface is a functional interface. This annotation is optional and must be used only when the interface is checked for compliance with the contract.

In Java, a Lambda expression must have a type and only one abstract method. Most of the existing callback interfaces already meet this requirement, therefore, you can reuse these interfaces without making any changes to them. For example:

// Before Java 8, Runnable r = new Runnable () {public void run () {System. out. println ("This shocould be run in another thread") ;}}; // Java 8 Runnable r = ()-> System. out. println ("This shocould be run in another thread ");

Java 8 provides a set of common functional interfaces for functions with parameters and return values. These interfaces are used in the java. util. function package as follows:

//Java 8Function<string, integer=""> parseInt = (String s) -> Integer.parseInt(s);

Because the parameter type can be inferred from the Function object type declaration, the type and parentheses can be omitted:

//Java 8Function<string, integer=""> parseInt = s -> Integer.parseInt(s);

For functions that require two parameters, Java 8 provides BiFunction:

//Java 8BiFunction<integer, integer="" integer,=""> multiplier =   (i1, i2) -> i1 * i2; //you can’t omit parenthesis here!

For interfaces that require three or more parameters, Java 8 does not provide corresponding TriFunction, QuadFunction, and other definitions, but you can define your own TriFunction, as shown below:

//Java 8@FunctionalInterfaceinterface TriFunction<a, r="" c,="" b,=""> {    public R apply(A a, B b, C c);}

After the previously defined interface is introduced, the Lambda expression can be declared as follows:

//Java 8TriFunction<integer, integer="" integer,=""> sumOfThree   = (i1, i2, i3) -> i1 + i2 + i3;

Why do Language designers stop at BiFunction? Hussachai Puripunpinyo believes that too many type declarations are required for interfaces that require more parameters such as TriFunction and QuadFunction, and the interface definition becomes very long, at the same time, how can we determine which one is the most appropriate? We cannot always define an EnnFunction that contains nine parameters and a return value type!

The preceding example shows that the more parameters there are, the longer the type definition, and even the whole row is a type declaration. Do you have to declare the type? The answer is that this is required in Java, but it is much simpler in Scala.

Scala is also a static and strong language, but it was a functional language since its birth. It perfectly integrates the object-oriented paradigm and functional language paradigm. Lambda expressions in Scala also have a type, but Language designers use numbers rather than Latin to name them. Scala provides developers with interface definitions of 0 to 22 parameters (Function0, Function1 ,... Function22). If more parameters are required, the developer may have problems in design. In Scala, the Function type is feature, similar to the abstract class in Java.

The Runnable example in Scala is different from that in Java:

// ScalaFuture (println {"This shocould be run in another thread"}) // The above code is equivalent to // Java 8 // assume that you have instantiated ExecutorService beforehand. runnable r = ()-> System. out. println ("This shocould be run in another thread"); executorService. submit (r );

In Scala, a Lambda expression does not have to explicitly specify the type as in Java, and there are many methods:

//Java 8Function<string, integer=""> parseInt = s -> Integer.parseInt(s);//Scalaval parseInt = (s: String) => s.toInt//orval parseInt:String => Int = s => s.toInt//orval parseInt:Function1[String, Int] = s => s.toInt

If you need more parameters:

//Java 8PentFunction<integer, integer="" integer,=""> sumOfFive   = (i1, i2, i3, i4, i5) -> i1 + i2 + i3 + i4 + i5;//Scalaval sumOfFive = (i1: Int, i2: Int, i3: Int, i4: Int, i5: Int) =>   i1 + i2 + i3 + i4 + i5;

Scala syntax is simpler and more readable. Developers do not need to declare the interface type. The type in the parameter list shows the object type.

//Java 8PentFunction<string, integer,="" string="" string,="" boolean,="" double,="">   sumOfFive = (i1, i2, i3, i4, i5) -> i1 + i2 + i3 + i4 + i5;//Scalaval sumOfFive = (i1: String, i2: Int, i3: Double, i4: Boolean, i5: String) => i1 + i2 + i3 + i4 + i5;

For the above Code, the developer can see that i3 is of the Double type, but in Java 8, the developer must count a few to see it, if you want to achieve this effect in Java 8, you have to write the article in the format:

//Java 8 PentFunction sumOfFive = (Integer i1, String i2, Integer i3, Double i4, Boolean i5) -> i1 + i2 + i3 + i4 + i5;

However, this is really bad. Developers must enter the type again and again. In addition, Java 8 does not define the PentFunction, and you must define it yourself:

//Java 8@FunctionalInterfaceinterface PentFunction<a, r="" c,="" b,="" e,="" d,=""> {    public R apply(A a, B b, C c, D d, E e);}

Hussachai Puripunpinyo believes that Scala is doing better in the functional way, on the one hand, because Scala itself is a functional language, on the other hand, because the Java Language designers must consider compatibility when introducing new things, therefore, there are many constraints. However, even so, Java 8 still introduces some very cool features, such as method reference, which can make the declaration of Lambda expressions shorter:

// Java 8 Function <string, integer = ""> parseInt = s-> Integer. parseInt (s); // method reference can be abbreviated as: // Java 8 Function <string, integer = ""> parseInt = Integer: parseInt;

In Java 8, there are three types of method reference building rules:

Stream APIs use this syntax extensively to simplify code writing:

pets.stream().map(Pet::getName).collect(toList());// The signature of map() function can be derived as//  Stream map(Function
  mapper)

Two days ago, I saw someone in a group who recommended an app to ask questions. They could answer questions, just like uber Didi took a taxi, generally, this kind of software throws money to give a red envelope. Brother has experience in using uber tickets before! I have tried it several times and I can use it to cash out the registered red envelopes and the money I received before. I have raised more than 50 yuan, and I can use it in visual testing. Ps, but try to ask technical questions, otherwise it will be easily blocked.

If you have any technical skills, you can try it by yourself. If you do not have any, you can ask my QQ Group 290551701

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.