程式扎記: [Scala IA] The Basics : Ch1. Why Scala - What’s Scala?

標籤

2016年6月24日 星期五

[Scala IA] The Basics : Ch1. Why Scala - What’s Scala?

What’s Scala? (p4) 
Scala is a general-purpose programming language that runs on Java Virtual Machine (JVM) and .NET platforms. But the recent explosion of programming languages on JVM, .NET, and other platforms raises a question that every developer faces today: which programming language to learn next? Which languages are ready for mainstream development? Among the heap of programming languages like Groovy, Ruby, Clojure, Erlang, and F#, why should you learn Scala? Learning a new language is merely a beginning. To become a useful and productive developer, you also need to be familiar with all the toggles and gizmos that make up the language infrastructure. 

Before I make the case for why Scala should be your next programming language, it’s important to understand what Scala is. It’s a feature-rich language that’s used in various types of applications, starting with building a large messaging layer for social networking sites such as Twitter to creating an application build tool like SBT (Simple Build Tool). Because of this scala-bility, the name of the language is Scala. 

This chapter explores the high-level features of the language and shows how they compare to the programming languages you may be very familiar with. This will help you to choose Scala as your next programming language. 

If you’re an object-oriented programmer, you’ll quickly get comfortable with the language; if you’ve used a functional programming language, Scala won’t look much different because Scala supports both programming paradigms. Scala is one of those rare languages that successfully integrates both object-oriented and functional language features. This makes Scala powerful because it gives you more in your toolbox to solve programming problems. If you have existing Java applications and are looking for a language that will improve your productivity and at the same time reuse your existing Java codebase, you’ll like Scala’s Java integration and the fact that Scala runs on the JVM platform


Scala is a general-purpose programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional programming languages, enabling programmers to be more productive. Martin Odersky (the creator of Scala) and his team started development on Scala in 2001 in the programming methods laboratory at EPFL (École Polytechnique Fédérale de Lausanne). Scala made its public debut in January 2004 on the JVM platform and a few months later on the .NET platform. 

Even though Scala is fairly new in the language space, it has gained the support of the programming community, which is growing every day. Scala is a rich language in terms of features available to programmers, so without wasting time let’s dive into some of them. 

Scala as an object-oriented language 
The popularity of programming languages such as Java, C#, and Ruby has made objectoriented programming (OOP) widely acceptable to the majority of programmers. OOP, as its name implies, is a programming paradigm that uses objects. Think of objects as data structures that consist of fields and methods. Object orientation helps to provide structure to your application using classes and objects. It also facilitates composition so you can create large applications from smaller building blocks. There are many OOP languages in the wild, but only a few are fit to be defined as pure object-oriented languages. 

What makes a language purely object-oriented? Although the exact definition of the term depends on whom you ask, most will agree a pure object-oriented language should have the following characteristics: 
 Encapsulation/information hiding.
 Inheritance.
 Polymorphism/dynamic binding.
 All predefined types are objects.
 All operations are performed by sending messages to objects.
 All user-defined types are objects.

Scala supports all these qualities and uses a pure object-oriented model similar to that of Smalltalk (a pure object-oriented language created by Alan Kay around 1980), where every value is an object, and every operation is a message send. Here’s a simple expression: 
In Scala this expression is interpreted as 1.+(2) by the Scala compiler. That means you’re invoking a + operation on an integer object (in this case, 1) by passing 2 as a parameter. Scala treats operator names like ordinary identifiers. An identifier in Scala is either a sequence of letters and digits starting with a letter or a sequence of operator characters. In addition to +, it’s possible to define methods like <=, -, or *. 

Along with the pure object-oriented features, Scala has made some innovations on OOP space (They will be covered in details on Ch3~Ch8): 
- Modular mixin composition 
This feature of Scala has traits in common with both Java interfaces and abstract classes. You can define contracts using one or more traits and provide implementations for some or all of the methods.

- Self-type 
A mixin doesn’t depend on any methods or fields of the class that it’s mixed into, but sometimes it’s useful to use fields or methods of the class it’s mixed into, and this feature of Scala is called self-type.

- Type abstraction 
There are two principle forms of abstraction in programming languages: parameterization and abstract members. Scala supports both forms of abstraction uniformly for types and values.

DEFINITION 
A mixin is a class that provides certain functionality to be inherited by a subclass and isn’t meant for instantiation by itself. A mixin could also be viewed as an interface with implemented methods.


Scala as a functional language (p6) 
Before I describe Scala as a functional language, I’ll define functional programming in case you’re not familiar with it. Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. 

Functional programming takes more of a mathematical view of the world, where programs are composed of functions that take certain input and produce values and possibly other functions. The building blocks of functional programming are neither objects nor procedures (C programming style) but functions. The simple definition of functional programming is programming with functions. It’s important to understand what is meant by functionhere. A function relates every value of the domain (the input) to exactly one value of the codomain (the output). Figure 1.1 depicts a function that maps values of type X to exactly one value of Y. 
Figure 1.1 A pure function that maps values of X to exactly one value of Y 

Another aspect of functional programming is that it doesn’t have side effects or mutability. The benefits of not having mutability and side effects in functional programs are that the programs are much easier to understand (it has no side effects), reason about, and test because the activity of the function is completely local and it has no external effects. Another huge benefit of functional programming is ease of concurrent programming. Concurrency becomes a nonissue because there’s no change (immutabilityto coordinate between processes or threads. You’ll learn about the functional programming side of Scala throughout the book, particularly in chapter 10. 

Now let’s talk about functional programming languages. Functional programming languages that support this style of programming provide at least some of the following features: 
 Higher-order functions (chapter 4)
 Lexical closures (chapter 3)
 Pattern matching (chapters 2 and 3)
 Single assignment (chapter 2)
 Lazy evaluation (chapter 2)
 Type inference (chapter 2)
 Tail call optimization (chapter 5)
 List comprehensions (chapters 2 and 4)
 Mondadic effects (chapter 5)

Scala supports most of them, but to keep it simple Scala is a functional language in the sense that functions are first-class values. That means that in Scala, every function is a value (like some integer value 1 or some string value "foo"), and like any values, you can pass them as parameters and return them from other functions. In Scala you can assign a function (x: Int) => x + 1 to a val inc and use that to invoke that function: 
scala> val inc = (x:Int) => x + 1
inc: Int => Int =

scala> inc(1)
res0: Int = 2

Here val represents a single assignment variable (like Java final variables) with a value that can’t be changed after the assignment. The output of the function call is 2. In the following example you’ll see how to pass functions as parameters to another function and get the result: 
scala> List(1, 2, 3).map((x:Int) => x + 1)
res0: List[Int] = List(2, 3, 4)

In this case you’re passing an increment function to another function called map, and the output produced by the invocation of the map function will be List(2, 3, 4). Based on the output you can see that map is invoking the given function for each element in the list. Don’t worry about the syntax right now; you’ll learn about it in detail in later chapters. 

Scala as a multi-paradigm language (p8) 
Scala is a multi-paradigm language because it supports both functional and OOP programming. Scala is the first to unify functional programming and OOP in a statically typed language for the JVM. The obvious question is why we need more than one style of programming. The goal of multi-paradigm computing is to provide a number of problem-solving styles so a programmer can select the solution that best matches the characteristics of the problem to be solved. This provides a framework where you can work in a variety of styles and mix the constructs from different ones. Functional programming makes it easy to build interesting things from simple parts (functions), and OOP makes it easy to adopt and extend complex systems using inheritance, classes, and so on. 

According to researcher Timothy Budd,5 “Research results from the psychology of programming indicate that expertise in programming is far more strongly related to the number of different programming styles understood by an individual than it is the number of years of experience in programming.” How can Scala combine these two different and almost opposite paradigms into one programming language? In the case of OOP, building blocks are objects, and in functional programming building blocks are functions. In Scala, functions are treated as objects

FUNCTIONS AS OBJECTS 
One of the benefits of combining functional programming with object-oriented programming in Scala is treating functions as objects. Scala, being a functional language, treats functions as values, and you saw one 
example of assigning a function to a variable. Because all values in Scala are objects, it follows that functions are objects too. Look at the previous example again: 
  1. List(123).map((x: Int) => x + 1)  
You’re passing the function (x:Int) => x + 1 to the method map as a parameter. When the compiler encounters such a call, it replaces the function parameter with an object, as in the following: 
  1. List(123).map(new Function1[Int, Int]{ def apply(x:Int): Int = x + 1})  
What’s going on here? Without diving in too deeply for now, when the Scala compiler encounters functions with one parameter, it replaces that call with an instance of class scala.Function1, which implements a method called apply. If you look carefully, you’ll see that the body of the function is translated into the apply method. Likewise, Scala has Function objects for functions with more than one parameter. As the popularity of multi-paradigm programming increases, the line between functional and object-oriented programming will fade away.6 As we continue to explore Scala, you will see how we blend both functional programming and OOP to solve problems. 

Scala as a scalable and extensible language (p9) 
Scala stands for scalable language. One of the design goals of Scala is to create a language that will grow and scale with your demand. Scala is suitable for use as a scripting language, as well as for large enterprise applications. Scala’s component abstraction, succinct syntax, and support for both object-oriented and functional programming make the language scalable. 

Scala also provides a unique combination of language mechanisms that makes it easy to add new language constructs in the form of libraries. You could use any method as an infix or postfix operator, and closures in Scala can be passed as “pass by name” arguments to other functions (see the next listing). These features make it easier for developers to define new constructs. 

Let’s create a new looping construct called loopTill, which is similar to the while loop in the following listing. 
- Listing 1.1 Creating the loop construct loopTill in Scala 
  1. def loopTill(cond: => Boolean)(body: => Unit): Unit = {  
  2.     if (cond)  
  3.     {  
  4.         body  
  5.         loopTill(cond)(body)  
  6.     }  
  7. }  
  8.   
  9. var i = 10  
  10. loopTill(i > 0)  
  11. {  
  12.     println(i)  
  13.     i -= 1  
  14. }  
In this code you’re creating a new loopTill construct by declaring a method called loopTill that takes two parameters. The first parameter is the condition (i > 0) and the second parameter is a closure. As long as the condition evaluates to true, the loopTill function will execute the given closure. 
DEFINITION 
Closure is a first-class function with free variables that are bound in the lexical environment. In the loopTill example, the free variable is i. Even though it’s defined outside the closure, you could still use it inside. The second parameter in the loopTillexample is a closure, and in Scala that’s represented as an object of type scala.Function0.

Extending a language with a library is much easier than extending the language itself because you don’t have to worry about backward compatibility. For example, Scala actor implementation (defined in section 1.2.2) is provided as a library and isn’t part of the Scala language. When the first actor implementation didn’t scale that well, another actor implementation was added to Scala without breaking anything. 

Scala runs on the JVM 
The best thing about Java is not the language but the JVM. A JVM is a fine piece of machinery, and the Hotspot team has done a good job in improving its performance over the years. Being a JVM language, Scala integrates well with Java and its ecosystem, including tools, libraries, and IDEs. Now most of the IDEs ship with the Scala plug-in so that you can build, run, and test Scala applications inside the IDE. To use Scala you don’t have to get rid of all the investments you’ve made in Java so far. Instead you can reuse them and keep your ROI coming. 

Scala compiles to Java byte code, and at the byte-code level you can’t distinguish between Java code and Scala code. They’re the same. You could use the Java class file disassembler javap to disassemble Scala byte code (chapter 11 looks into this in more detail) as you could for Java classes. Another advantage of running Scala on a JVM is that it can harness all the benefits of JVM-like performance and stability out of the box. And being a statically typed language, Scala programs run as fast as Java programs.

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!