In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
The purpose of this article is to share with you what the Scala control structure refers to. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article.
So far in this series, we have discussed the fidelity of Scala to the ecological environment, showing how Scala combines many of the core object functions of Java. If Scala were just another way to write objects, it wouldn't be noticeable, or less powerful. The combination of Scala's concepts of function and object, and its emphasis on programmer efficiency, make learning the Scala language more complex and subtle than Java-cum-Scala programmers imagine.
For example, use the Scala method for control structures such as if, while, and for. Although these control structures look similar to some of the old and decent Java structures, Scala actually adds some completely different features to them. This month's article is an introduction to what you can expect when using the Scala control structure, rather than risking setbacks to look for differences after making a lot of errors (and writing a bunch of error codes).
Revised Person.scala
Scala can define POJO by defining methods that mimic the traditional "getter and setter" required for POJO-based environments. After this article was published, I received an email from Bill Venners that Bill Venners was about to be published officially, and Bill pointed out an easier way to do this, using scala.reflect.BeanProperty tagging, as follows:
Listing 1. Modified Person.scala
Class Person (fn:String, ln:String, a:Int) {@ scala.reflect.BeanProperty var firstName = fn @ scala.reflect.BeanProperty var lastName = ln @ scala.reflect.BeanProperty var age = "[Person firstName:" + firstName + "lastName:" + lastName + "age:" + age + "]"}
The method in listing 1 generates a get/set method pair for the specified var. The only drawback is that these methods don't actually exist in Scala code, so other Scala code cannot call them. This is usually not a big deal, because Scala will use the generated methods for the fields generated for itself; if you don't know in advance, these may come as a surprise to you.
What strikes me most after looking at the code in listing 1 is that Scala doesn't just demonstrate the power of combinatorial function concepts and object concepts, it also demonstrates some of the benefits of object languages in the 30 years since the release of Java.
Control is a fantasy.
Many of the strange and incredible things you'll see can be attributed to the functional nature of Scala, so it might be useful to briefly introduce the background of functional language development and evolution.
In functional languages, it is not common to build more and more advanced structures directly into the language. In addition, language is defined by a set of core primitive structures. Combined with the ability to pass functions as objects, the higher-order functions that can be used to define functions may seem beyond the scope of the core language, but it is really just a library. Like any library, this feature can be replaced, extended, or extended.
The compositing features of building languages based on a set of core primitives have a long history, dating back to the use of Smalltalk, Lisp, and Scheme in the 1960s and 1970s. Languages such as Lisp and Scheme are highly sought after for their ability to define a higher level of abstraction at a lower level of abstraction. Programmers can use high-level abstractions to build higher-level abstractions. When you hear about this process today, it's usually about domain-specific languages (or DSL) (see Resources). In fact, it's just about the process of how to build an abstraction on top of it.
In the Java language, the only option is to do this with an API call; in Scala, it can be done by extending the language itself. Trying to extend the Java language carries the risk of creating extreme scenarios (corner case) that threaten global stability. Trying to extend Scala simply means creating a new library.
If structure
We'll start with the traditional if structure-- which, of course, has to be one of the easiest to deal with, isn't it? After all, in theory, if checks only one condition. If the condition is true, the code that follows is executed.
However, this simplicity can be deceptive. Traditionally, the Java language uses the else clause of if casually, and assumes that if the condition goes wrong, you can just skip the code block. But in function statements, this is not the case. In order to preserve the arithmetic nature of function statements, everything must be evaluated as an expression, including the if clause itself (for Java developers, this is how the ternary operator--?: expression-- works).
In Scala, the untrue code block (the else part of the code block) must be rendered in the same form as the value in the if code block, and must produce the same kind of value. This means that no matter how the code is executed, it always produces a value. For example, see the following Java code:
Listing 2. Which profile? (Java version)
/ / This is Java String filename = "default.properties"; if (options.contains ("configFile")) filename = (String) options.get ("configFile")
Because the if structure in Scala is an expression itself, rewriting the above code will make them a more correct code snippet shown in listing 3:
Listing 3. Which profile? (Scala version)
/ / This is Scala val filename = if (options.contains ("configFile")) options.get ("configFile") else "default.properties"
That is, Scala programmers should usually * val structures and choose var when there is a clear need for variability. The reason is simple: in addition to making programming easier, val ensures the thread safety of programs, and an inherent theme in Scala is that you don't really need to change state almost every time you think you need it. Let's start with no mutable fields and local variables (val), which is one way to demonstrate this, even for the most staunch Java skeptics. It may not be reasonable to start with final in Java, perhaps because of the non-functional nature of Java, although this reason is not desirable. Some curious Java developers might want to try it.
Although the real winner is Scala, you can assign the result to val, not var, by writing code. Once set, the val cannot be changed in the same way as the final variable in the Java language. The most significant side effect of immutable local variables is that concurrency is easy to achieve. When you try to do the same with Java code, you get a lot of good, readable code, as shown in listing 4:
Listing 4. Which profile? (Java version, ternary)
/ / This is Java final String filename = options.contains ("configFile")? Options.get ("configFile"): "default.properties"
It may take some skill to explain this with a code review. Maybe this is the right thing to do, but many Java programmers will disagree and ask, "Why are you doing that?"
Val and var
You may want to know more about the difference between val and var, but in fact, the difference is that one is a read-only value and the other is a variable. In general, functional languages, especially those that are considered "pure" functional languages (with no side effects, such as variable state), only support the concept of val; however, because Scala attracts both functional programmers and command / object programmers, it provides both structures.
Disclosed while structure
Next, let's take a look at while and his compatriot do-while. They do basically the same thing: test a condition, and if the condition is true, continue to execute the provided block of code.
In general, functional languages avoid while loops because most of the operations implemented by while can be done using recursion. Functional languages are really very similar to recursion. For example, consider the quicksort implementation shown in "Scala by Example" (see Resources), which can be used with the Scala implementation:
Listing 5. Quicksort (Java version)
/ This is Java void sort (int [] xs) {sort (xs, 0, xs.length-1);} void sort (int [] xs, int l, int r) {int pivot = xs [(lumbr) / 2]; int a = l; int b = r; while (a pivot) {b = b-1;} if (a new URL ("www.tedneward.com")}
The code in listing 8 is a far cry from the code in the if example in listing 2 or listing 3. In fact, it's more tricky than writing in traditional Java code, especially if you want to capture values stored in immutable locations (as I did in the last example in listing 4). This is another advantage of Scala's functional features!
The case ex: syntax shown in listing 8 is part of another Scala structure (matching expression) that is used for pattern matching in Scala. We'll look at pattern matching, a common feature of functional languages, which we'll cover later; for now, just think of it as a concept that will be used for switch/case, so which C-style struct will be used for classes?
Now, consider exception handling again. As we all know, Scala supports exception handling because it is an expression, but what developers want is a standard way to handle exceptions, not just the ability to catch exceptions. In AspectJ, you do this by creating aspects (aspect) that are linked around parts of the code that are defined by pointcuts, and if you want different parts of the database to behave differently for different kinds of exceptions, you must carefully write these pointcuts-- SQLExceptions should be handled differently from IOExceptions, and so on.
In Scala, this is just a trivial detail. Please watch carefully!
Listing 9. A custom exception expression
/ / This is Scala object Application {def generateException () {System.out.println ("Generating exception..."); throw new Exception ("Generated exception");} def main (args: Array [String]) {tryWithLogging / / This is not part of the language {generateException} System.out.println ("Exiting main ()") } def tryWithLogging (s: = > _) {try {s} catch {case ex: Exception = > / / where would you like to log this? / / I choose the console window, for now ex.printStackTrace ()}
Similar to the While structure discussed earlier, the tryWithLogging code is just a function call from a library (in this case, from the same class). You can use different theme variables where appropriate, without having to write complex pointcut code.
The advantage of this approach is that it takes advantage of Scala's ability to capture crosscutting logic in a first-level structure-- which only aspect-oriented people could declare in the past. The first-level structure in listing 9 catches some exceptions (both checked and unchecked) and handles them in a specific way. The side effects of the above ideas are so many that the only limitation may be imagination. You just need to remember that Scala, like many functional languages, allows you to use code blocks (aka functions) as arguments and use them as needed.
For generation language
All of this leads us to the actual power source of the Scala control structure suite: the for structure. This structure looks like a simple early version of Java's enhanced for loop, but it is far more powerful than the average Java programmer first imagined.
Let's take a look at how Scala handles simple sequential iterations on collections, and based on your Java programming experience, I think you should know exactly what to do:
Listing 10. Use for loops for one object and for loops for all objects
/ / This is Scala object Application {def main (args: Array [String]) {for (I
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.