In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
What is the Lambda expression in Scala and why to use the Lambda expression, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.
Java8 is finally going to support Lambda expressions! Lambda expressions have been supported in Lambda projects since 2009. At that time, Lambda expressions were still called Java closures. The following editor will explain why Lambda expressions are used. What is the Lambda expression in Scala?
Why use Lambda expressions
Lambda expressions are commonly used in graphical user interface (GUI) development. Generally speaking, GUI programming connects program behavior to events. For example, when a user presses a button (triggering an event), your program needs to perform some behavior, perhaps storing some data in a data store. In Swing, you can use ActionListener to do this:
ClassButtonHandlerimplementsActionListener {
PublicvoidactionPerformed (ActionEvente)
{
/ / dosomething
}
}
ClassUIBuilder {
PublicUIBuilder () {
Button.addActionListener (newButtonHandler ())
}
}
This example shows the use of the ButtonHandler class as a callback replacement. Here the ButtonHandler class contains only the actionPerformed methods defined by the ActionListener interface. We can use anonymous inner classes to simplify the code:
ClassUIBuilder {
PublicUIBuilder () {
Button.addActionListener (newActionListener () {
PublicvoidactionPerformed (ActionEventevent) {
/ / dosomething
}
})
}
}
This makes the code much simpler. When you take a closer look at the code, you will see that we also create a class that generates only one instance, which only holds a separate method. This is exactly one of the kinds of problems that Lambda expressions can solve.
Lambda expression instead of function
An lambda expression is literally a function. It defines the input parameters and the body of a function. The syntax of the lambda expression in Java8 has not been determined, but it should look something like this:
(typeparameter)-> function_body A specific example:
(Strings1,Strings2)-> s1.length ()-s2.length ()
This lambda expression is used to calculate the length difference between two strings. There are also some extended syntax, such as avoiding type definitions of parameters (we'll see examples in a moment) and using {and} to support multi-line definitions.
Collections.sort ()
Method is an ideal example of lambda expression. It allows us to sort strings by length:
Listlist=Array.asList ("loooooong", "short", "tiny")
Collections.sort (list, (Strings1,Strings2)-> s1.length ()-s2.length ())
"tiny", "short", "loooooong".
So, instead of typing an implemented Comparator (comparator) into the sort method, as java must now require, we can get the same result by passing an lambda expression.
Lambda expressions instead of closures
Lambda expressions have many interesting features. One of them is that they are closures. A closure allows a function to access variables outside the direct lexical scope.
Stringouter= "java8" (Strings1)-> s1.length ()-outer.length ()
In the example, the lambda expression accesses a variable defined outside the scope of the string outer. This is difficult for inline closures.
Lambda expressions also support type inference
Type inference was introduced by java7, but it also applies to lambda expressions. Simply put, type inference means that programmers can omit type definitions anywhere a compiler can automatically infer types. If the type inference can be applied to the previous sort lambda expression, it can be written as follows:
Listlist=Arrays.asList (… )
Collections.sort (list, (s1mems2)-> s1.length ()-s2.length ())
As you can see, the types of parameters S1 and S2 are omitted. Because the compiler knows that list is a collection of strings, it knows that lambda expressions used as comparators must be of the same type. Therefore, this type does not need to be explicitly declared, even if you have the freedom to do so.
The main advantage of type inference is to reduce boilerplate code, and if the compiler can identify types for us, why do we have to define them ourselves.
Cherish Lambda expressions and stay away from anonymous inner classes
Let's see why lambda expressions and type inferences help simplify the callback example we mentioned earlier:
ClassUIBuilder {
PublicUIBuilder () {
Button.addActionListener (e-> / / processActionEvente)
}
}
We download and pass a lambda expression directly into the addActionListener method instead of the previously defined class that holds the callback method. In addition to reducing template code and improving readability, it allows us to express directly the only thing we are interested in: handling events.
Before we learn more about the advantages of lambda expressions, let's take a look at a copy of lambda expressions in Scala.
What is the Lambda expression in Scala
In functional programming, functions are the basic building blocks. Scala combines object-oriented programming and functional programming in java. In Scala, a lambda expression is called "function" or "function text". Functions in Scala are first-class citizens. They can be assigned to vals or vars (final variable or non-final variable), they can be used as arguments to other functions, or they can be combined into new functions.
In Scala, the text of a function is written as follows:
(argument) = > / / funtionbody
For example, the aforementioned lambda expression used by java to evaluate the length difference between two strings is written in Scala as follows:
(s 1 s1.length-s2 String.s 2)
The function text in lengthScala is also a closure. It can access variables defined outside the direct lexical scope.
Valouter=10valmyFuncLiteral= (y:Int) = > y*outervalresult=myFuncLiteral (2) > 20 the result is 20.
As you can see, we assigned the function text to the variable myFuncLiteral.
The grammatical and semantic similarities between java8's lambda expression and Scala's function text are very obvious. They are the same semantically, while the only grammatical differences are arrow symbols (java8- >, scala= >) and simplified symbols that we did not mention.
This is the answer to the question about what the Lambda expression in Scala is and why you use the Lambda expression. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.