Scala is really awesome.

Source: Internet
Author: User

I do think that the school of Computer Science should open a Scala language course.

In this article, I'll tell you why I have this idea, and before that, there are a few things I would like to declare first:

This article does not intend to evaluate the programming language, I want to tell the subject is why you should learn Scala. 51CTO has published an article about why Java programmers are learning Scala, and may be helpful to you.

Scala now has two implementations, one running on the JVM (Java virtual machine) and the other running on the CLR (Common Language runtime abbreviation, the common language runtime). However, the implementation of the JVM is more mature. If you want to use the. Net Framework framework, I think it's best to follow the advice of Lift framework founder David Polac David Pollack: Using F #. But in this article, I'll just focus on how the JVM is implemented.

I am a ruby programmer and I will continue to like Ruby because it is the best dynamic language I have ever seen. But I also like Scala, because in other areas of work, it offers some very powerful features.

Now, let's take a closer look at some of the reasons why I chose Scala as my next programming language:

Powerful programming language

Scala is a very powerful language that allows users to write code using commands and function paradigms, so you can use commonly used imperative statements when programming, just like we do with C, Java, PHP, and many other languages, and you can use functional statements like the Lisp language, as well as , you can mix these two styles of statements, just like Ruby or Groovy.

However, when we talk about the function paradigm, it's a little different from Ruby and Groovy that Scala almost supports all known functions in the function language, such as pattern matching (matching), lazy initialization (lazy initialization), partial functions (partial function), invariance (immutability), etc... That is to say, it is important to recognize the fact that Scala's power stems from its support for the functional paradigm, which makes Scala a high-level (high-level) programming language. For a high-level programming language, you need to focus on what you do rather than how.

Below, let's look at a Java example:

int[] x = {1,2,3,4,5,6};   ArrayList res = new ArrayList ();   for (int v:x) {if (v 2 = = 1) res.add (new Integer (v)); Take a closer look at the example code above, and you'll notice that the "what" Part I want to do (filtering out the odd values) only appears in line fourth, while the rest of the lines are the parts of how to do it (the initialization of the result variable and a looping operation). If I want to write a filter to filter even values, then you need to write five lines of code, and using a high-level language like Scala, you just write the "what" part of the Code:

Val x = Array (1,2,3,4,5,6) Val res = x Filter (_% 2 = = 1)//filter Odd value Val res2 = x Filter (_% 2 = = 0)//filter Even values we can see that This code is more concise and more readable than the Java code snippet in the preceding paragraph.

Efficient

Scala is an efficient programming language, and in fact, it's almost as fast as Java, based on the latest benchmark performance tests. The Scala code implemented on the JVM can be compiled into bytecode, during which the code compiles through the optimization phase. Tail recursion optimization is a good example that helps users focus on functional paradigms without sacrificing performance. Another example is the optimizations that are made when you convert a Scala value type object to a Java base type.

Can be extended

The Scala language itself is named Scala from the scalable (extensible) term, which means that the language can be scaled to the needs of the user. Thus, fundamentally, users can add new types and control structures. For example, I want to add a simple "loop" control structure:

A simple build def loop (Range:range) (op:int=> Unit) {range foreach (OP)} loop (1 to 5) {println}//1 2 3 4 5 Loop (1 to 5) {x = = if (x% 2 = = 0) println (x)}//2 4 There are several more complex examples, Actor Lib, which is added as an extension to the language of Scala, and we will discuss it in the following article.

However, the reason Scala is extensible is that it is an interrelated two point: it is a true object-oriented language and a true functional language.

Object oriented

Everything in Scala is an object (except for object methods), so it is not necessary to differentiate between basic (primitive) types or reference types, which is what is called: the Unified Object Model (Uniform). However, as I mentioned earlier in the optimization process, value type objects are converted to Java primitives, so there is no need to worry about performance issues. It also contains a single-piece object (Singleton object) that is grouped into class methods.

All operations are method calls, +-*! /are methods, so there is no need for operator overloading.

With very granular access control, users can control access to certain methods of some packages.

Scala has trait, similar to mixin in Ruby, like interfaces in Java, but implements some of their methods, so the user has a rich wrapper (wrapper) and Rich interface (interface) outside the box.

Functional language

Functional languages have many features, but in the context of extensibility, we are concerned with two facts:

The function is the value of the first level (first-class)

This means that the user can pass the function as a value, or it can be returned as a value. This allows for concise and readable code, as in the example filter snippet above.

Purely functions (pure function)

Scala supports pure functions with no side effects, which means that if your input is the same, the output will always be the same. This will make the code more secure and more convenient for code testing.

But how does Scala support pure functions? Pass invariance (immutability): Biased references (similar to constant in final or other languages in Java) and unchanging data structures that cannot be modified once created.

Immutability is a security guarantee that has pure functions, but is not the only way. Without immutability, you can still write secure code. That's why Scala does not enforce immutability and just encourages its use. Eventually, you'll find that many of the data structures in Scala have two implementations, one variable, the other immutable, and immutable data structures that are imported by default.

When it comes to immutability, some people start worrying about performance, and in some cases this is not the case, but for Scala, the end result is the opposite of that worry. The immutable data structure can be more efficient than the variable data structure. One reason for this is the powerful garbage collector (garbage collector), similar to the garbage collector in the JVM.

Better parallel model

When it comes to threading, Scala supports the traditional shared data model. However, after using this model for a long time, many people find it very difficult to implement and test using this model to write code. You always need to consider deadlock problems and competitive conditions. As a result, Scala provides another parallel model called actor, where the actor sends and receives non-synchronized information through its inbox, rather than sharing data. This approach is called: Shared nothing model. Once you no longer worry about sharing data, you don't have to worry about code synchronization and deadlock problems.

The invariant nature of the information being sent and the serial processing in the actor make it easier to support parallelism.

For Scala parallel issues, please see this article for a better understanding of this concept.

Before I tell you the next point, I need to mention the fact that some people see the use of actors as an evolution of programming languages. Just like the advent of Java, the advent of Scala, which rescued programmers from the mud of pointers and memory management, has made it possible for programmers to avoid the need to synchronize their code and share data models all day long.
Static type

When I wanted to tell this point, I found that I was trying to give the same attention to both sides of the static type language. In fact, the debate on this topic is always endless, but I would like to make a two-point summary, and these two points are the hotspots that most people discuss:

Code written in a static type language is more robust (robust)

The existence of TDD makes many of the discussions about dynamic type languages and robust code meaningless, although this is true, when we still cannot ignore the fact that for dynamic type languages you need to write more test code to check the type, and in a static type language, you can leave these issues to the compiler for processing. In addition, there are those who think that your code will have a better self-documenting use of statically typed languages.

Code written in a static type language is too restrictive and lengthy

Fans of dynamic-type languages like me think that a more dynamic code structure can be written by duck type (duck typing). But they also complain that statically typed languages cause code to be lengthy.

For a debate about static types and dynamic types, you can see more information in this article published before 51CTO.

As a statically typed language, Scala has the advantages mentioned in the first article, but what about the 2nd?

Scala has a flexible type system and may be the best of its kind. In many cases, if you do not specify a type, the system will be able to infer the type.

For example, you could write code like this:

Val list:list[string] = list ("One", "one", "one", "three")//list:list[string] = list (one, both, three) Val s:string = "H   Ello world! " s:java.lang.string = Hello world! But you can also write code like this:

Val list = list ("One", "one", "one", "three")//list:list[string] = list (one, both, three) Val s = "Hello world!" s:java.lang.string = Hello world! Very well, anyway, it solves the problem of lengthy code. But what about a problem like duck type (duck typing)?

The answer is: The Scala type system has some flexibility that allows you to write code like this:

def eat[t <: Animal] (a:t)//whatever where we define type T as a subtype of Animal. You can also be more flexible:

def eat[t <: {Def eat (): Unit}] (a:t)//whatever where we define type T as a type with an illegal eat.

In fact, the Scala type system is very rich and you can find more information here.

Pattern matching

I had to confess, after a long pause, that I decided to write about this feature of Scala. In fact, I wasn't going to discuss Scala's function, but when I saw an article about the object Branch (switch) app, I thought it was important to talk about this feature. The following basically comes from this blog post:

What exactly is a pattern match for? It allows you to match a value to multiple cases (case), somewhat like a branch (switch) statement in Java. But instead of just matching numbers (which is what branch statements do), it is the ability of the user to match things that are inherently created in the form of objects (creation form).

The following example also comes from the blog mentioned above:

X Match {case Address (Name (first, last), Street, city, state, zip) = = println (last + "," + Zip) Case _ = = Prin TLN ("Not an Address")//Default condition} for the first case, the pattern Name is nested in the schema address (...). The last value, which is passed to the Name constructor and then extracted, is therefore available in the expression on the right side of the arrow.

So

The meaning of pattern matching

Why do you need pattern matching? We all have complex data. If we stick to strict object-oriented programming, then we don't want to focus on the internal context of the data tree. Instead, we want to invoke methods that allow methods to do these things. If we have the ability to do this, we will not need pattern matching very much, because the method satisfies our requirements. However, many times objects do not have the methods we need, and we cannot (or do not) add new methods to the objects.

Therefore, pattern matching is considered an effective method of gaining extensibility, and it provides a good solution to the problem, except for the lengthy design patterns that the visitor has caused.

In any case, it is highly recommended that you look at the section "Two Directions of extensibility" (two Directions of extensibility) in the article mentioned above.

Simple DSL (domain-specific language)

Writing a Dsl,scala is a good choice. In fact, Scala works for both internal and external DSLs. In this article, you can find a comparison of some of the features of using Ruby and Scala to write internal DSLs. The following article is also great for writing an internal DSL using Scala: The Boolean Algebra Internal DSL in Scala (aka Fun with Unicode names).

In addition, for external Dsl,scala should be the preferred language, the reason behind is the parser combination subpackage (Parser combinator Lib), it makes it a cool thing to write compilers for the new language.

Interoperability with Java code

The implementation of Scala's programs on the JVM can be seamlessly integrated with the Java platform, and many Scala types are actually compiled into Java types, so users can safely use Java types. You can also use the JVM language to program in a mixed way, such as JRuby, Groovy, Clojure, and so on. Here's a good article that provides this example.

Learning-oriented language

I have two habits, and in Scala's learning process, I have insisted on these two habits:

Meet new technical terminology, access Wikipedia to understand more information, such as function literal (text function), referentially transparent (referential transparency), partial function (partial functions), Currying (Coriwa), there are many other terms.

Refer to my understanding of other languages to see if the meanings of these terms are fulfilled.

With some good practice, such as writing pure functions without side effects, concentrating on the "what" part of the code, and handing over the "how" section to the language, these two habits give me more knowledge and improve the quality of the code.

Team

Designed by Martin Odeski Martin Odersky, Scala is a manager at the Swiss Federal Institute of Technology, Lausanne (EPFL) laboratory group of programming methods. Odeski had been employed by Sun to write the Java 1.1 compiler, and he was the Javac major developer of Java 1.1 to Java 1.4. In addition, he is the author of Java generics. 51CTO editors communicated with Odeski on the language features of Scala via e-mail and received a reply to the following letters.

Scala is now maintained by Odeski and his team at the Swiss Federal Institute of Technology, Lausanne. However, there are other talented developers involved who, through years of work, have worked together to create the Scala programming language.

Source

Scala is inspired by a variety of languages:

Most of the syntax comes from Java and C #.

Other elements also come from Java, such as the basic type, the class library, and its running model.

The Unified object model it uses is the first used by Smalltalk.

The concept of universal nesting (universal nesting) also appears in Algol, Simula, and recently in Beta and Gbeta.

The method of functional encoding is also mentally similar to the ML language family, which contains SML, OCaml, and the most important member of F #.

Many of the higher-order functions in the Scala standard library also appear in ML and Haskell.

Scala's implicit parameters are also inspired by the Haskell type class. Scala's actor-based parallel libraries are primarily inspired by Erlang.

Consider the insert (infix) operator as a function and allow text functions (or block blocks) as parameters to enable libraries to define control structures that can be traced back to Iswim and Smalltalk.

Expert opinion

In fact, such words as James Strakan (James Strachan: the founder of programming language Groovy) are a bit of a surprise:

To be honest, if someone gave me a copy of Bill Vennas in Scala, co-authored by Martin Odeski (Martin Odersky), Lex Spenn (Lex Spoon) and Venners (Bill programming) in 2003 years, I'm probably not going to create Groovy again.

Before concluding, let me summarize:

I like Scala because it is an efficient, learning language, has a good parallel model, and is ideal for writing DSLs.

Scala is really awesome.

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.