Scala (programming language)

Scala is a functional and object-oriented programming language.

The name derives from ' scalable language' from and expresses that the very compact held core language provides the ability to implement language frequently used items such as operators or additional control structures in user classes and thereby expand the language range and its own domain-specific languages ​​(English domain-specific language, DSL) to create.

  • 3.4.1 Covariance and contravariance
  • 3.4.2 Type Inference
  • 4.1 operators
  • 4.2 grinding
  • Scala 5.1 2.8
  • Scala 5.2 2.9
  • 5.3 Scale 2:10

Examples

A 'Hello, World! Program in Scala:

Object HelloWorld extends App {    println ("Hello, world!" ) } An implementation of the quicksort algorithm:

Def quicksort [A <% Ordered [ A] ] ( xs: List [A]): List [A ] = xs match {    case Nil => xs    case y :: ys => ys partition ( _ < = y) match {      case (l1, l2 ) = > quicksort (l1 ) ( y :: QuickSort (l2 ) ) } } history

Scala is developed in the laboratory of programming methods at the École Polytechnique Fédérale de Lausanne in Switzerland, under the direction of Martin Odersky.

Martin Odersky worked Niklaus Wirth in Modula 2 and Oberon. In 1995 he developed together with Philip Wadler language pizza Java to generics, function pointers, and advanced pattern matching. Later, Wadler and Odersky concentrated with Generic Java ( GJ) on Generics for Java, this project led in 2004 to the introduction of generics in Java. As of 1999, Martin Odersky worked at the École Polytechnique Fédérale de Lausanne, where he conducted research on the connection of functional and object-oriented programming and developed the minimalist hybrid language Funnel. Here he began in 2001 with the development of Scala, which, unlike Funnel should serve not purely academic interest, but was designed as a full-fledged language for real-world applications. In spring 2004, Scala was released for the Java Platform, in June 2004. NET.

Since early 2011, the development of the language from the European Research Council is funded. This will be expanded in particular the possibilities of parallel programming.

On 12 May 2011 Martin Odersky announced the launch of Typesafe known; a company that the commercial support of Scala in general and the Akka middleware framework dedicated to. The consultants include James Gosling and Doug Lea.

Concepts

Integration with Java

Scala programs can respond Java JARs and vice versa. It can be integrated into Scala projects where it is used so all existing Java libraries and frameworks. The same applies to most of the tools: development environments such as Eclipse, NetBeans or IntelliJ Scala support also.

Object orientation

Scala, unlike Java, a pure object- oriented programming language. Each value is an object. This is also true for primitive data types, without causing performance degradation, since the byte code generated by the compiler uses primitive data types.

Interfaces implemented by the mechanism of traits. Traits not only consist of definitions, it may already contain concrete implementations of methods. Classes can extend one or more traits ( extends keyword ). This is not about multiple inheritance, but a mixin mechanism.

The keyword object (instead of class ) is an implementation of the Singleton design pattern provided.

Functional language

Functions are first-class objects. They can be used at all locations where values ​​are allowed, such as assignment to a variable ( here is not the result of the function evaluation meant, but the functions themselves ) or when passing parameters. Methods can always be converted into functions, but are themselves not first-class objects. Also, higher order functions are implemented in Scala.

Currying

If the signature of a method contains n parameter lists, but is called with only one parameter list, it delivers using the passed parameter list returns a ( unnamed ) method with n-1 parameter lists.

Pattern Matching

An important aspect in support of functional programming with Scala 's pattern matching. In contrast to the switch statement, as implemented, for example, Java, pattern matching does not work only on the basis of values ​​, but also based on the structure or the type of an object. Among other things, this Case Classes were implemented in Scala.

The following code implements the search in a binary search tree using Pattern Matching and Case Classes:

Abstract class Tree case class Leaf ( key: Int) extends Tree case class Fork ( key: Int, left: Tree right, : Tree ) extends Tree   def contains ( tree: Tree, key: Int): Boolean = tree match {    case Leaf ( i) = > i == key    case Fork (i, _, _) if i == key = > true    case Fork ( i, left, _ ) if key < i = > contains ( left, key)    case Fork (i, _ right, ) if i < key = > contains ( right, key)    / / Default case    case _ = > sys.error ( "should not happen! " ) } Closures

Functions access not only to their parameters and local variables, but also to its context variables (Scope ), which are valid at the time of evaluation. This will open terms of the eponymous closed terms. If case of multiple use of the function changes the value of a variable of the context to a former time of evaluation, also the return value and the behavior of the function can change.

Type System

Scala is statically typed. Generic classes use types that are not yet determined at the time of development, such as List [T ] Upper class abstract types can pretend to be specified by its subclasses in the form of concrete types. The same applies to variables (var and val ), and methods.

Covariance and contravariance

Type parameter of a generic class can be provided with an annotation that determines how subtype relations of type arguments affect the subtype relation of generic instantiations of the class. Invariance, syntax: K [T ], means that no link exists. Covariance Syntax: K [ T], means that the relationship continues in the same direction: If T is subtype of U, then K [T ] is subtype of K [ U]. Contravariance Syntax: K [ T ], it means that the sequel takes place in the opposite direction: If T subtype of U, then K [ U] is subtype of K [ T]. Influence Varianzannotationen, may be used at what point within the generic class of type parameters: covariant type parameters may for example not be used as a type of method arguments, not contra-variant return type.

Type inference

Type inference is the ability of the compiler to infer the type of an expression from the context, which is exemplified in the Syntax.

Evaluation strategy

Functional expressions are evaluated strictly in Scala. However, may be specified by the keyword lazy lazy evaluation ( lazy evaluation) of individual expressions. The collection classes support using the methods view and force the possibility of lazy evaluation. In contrast, in Haskell programs are evaluated by default lazy and there are strictness annotations.

XML

In the standard libraries fundamental XML operations and data types are available: XML literals, constructors, serialization and deserialization, XPath -like extraction of elements and attributes:

Val list =                  

bread < / name> 3:50 < / article >                  
apple < / name> 12:29 < / article >                  
eggs < / name> 1:19 < / article >                     val total price = ( list \ \ " award "). map ( _.text.toDouble ). sum     / / Result: 4.98 Implicits

Methods by means of the implicit Modifiers are so-called implicit methods. When the compiler encounters an object of a given type A expected, but an object of incompatible type B, it searches the lexical scope and in the companion object of A for a implicit method, with which he can convert the B object to an A- object. With this technique, known from C # extension methods can be replicated ( the so-called pimp my library pattern) and within limits even heredity.

The last parameter list of a method can also be marked as implicit. If the parameter list when calling a method is missing, but can be found as implicit marked value in the lexical scope, it will be automatically passed to the method. This makes it possible to replicate from Haskell type classes known as design patterns.

With implicit conversions and behavior in libraries is implemented in Scala, which cover many languages ​​as a special case in the compiler. For example, special rules when joining strings like 42 " some text " or the conversion of numeric types with a smaller range of values ​​to integer types with a larger range of values ​​in Java string concatenation operator or widening called primitive conversions.

Concurrency

While Scala threads supported by the Java class library, there is Scala's own library, an implementation of actuators. This was inspired by the actuators implementation, as it has been implemented in Erlang. From the Scala version 2.11 the original actuators implementation will no longer be part of the standard library. Replaces it is ( available since version 2.10) by the Akka implementation.

Syntax

The syntax of the language is based on Java and ML. From Java in particular a number of key words and the block syntax was taken from the ML syntax for Typannotationen and declarations.

Compared to the Java syntax, the semicolon may be omitted at the end of a line in most cases. The syntax for type definition of variables and return values ​​is modeled on the ML instead of Java: you do not formulated type variable, but variable: type.

The declaration and definition of values ​​, variables, and methods by means of the keywords val, var and def, followed by type information.

Val value: Int = 42     var variable: Double = 3:14     def method ( parameter1: String, parameter2: Boolean): Unit The compiler infers the type of a variable from the context from ( type inference ). The two lines

Var x = "Some text " and

Var x: String = "Some text " are thus equivalent.

Class and method names can use a large amount of characters and symbols. There are, for instance identifier such as , *, ::, \ \ or isEmpty_? allowed.

Method calls with no or one parameter can, with the omission of the point and the opening and closing parentheses are listed (similar to Smalltalk or Objective- C):

5.0. ( 2.0)      "Test". StartsWith ( "T")      List ( 1,2,3). IsEmpty corresponds

5.0 2.0      "Test" start with " T"      List ( 1,2,3) isEmpty With Scala, it is also possible to write the source code compared to Java compact in many cases, for example on the basis of inference, for comprehensions or anonymous functions.

Operators

For prefix operators, there is a fixed, predetermined amount, namely , -, ~, and! . The term -x means the same as x.unary_ -

Postfix - expression are also possible. There are no restrictions to the operator, and the translation result is a call to the ( parameterless) constructor method on the operands.

In infix operators, the first character of operator precedence and associativity name via which follows the usual conventions from mathematics decides. The code fragment

1 z * x is translated to

(1). (For * (x)) The method is called and the parameters for * (x ), ie the result of another method call passed to the object 1.

Ends the method name of a Infixoperators with a colon, then changed the order of the receiver and parameters and the operator is right- associative:

A :: b is translated to

B. :: ( a) grind

For loops were called for comprehensions insofar as generalized, that they not only combine several nested loops, but can be used to Haskell's do- notation arbitrary monads analog.

This code is for example 27 rows for each value of a, b ​​and c from.

For {    a < - List ( 1,2,3)    b < - List ( 2,3,4)    c < - List ( 5,6,7) Println } ("a =" a " b =" b ", c =" c ) A for comprehension can also be used to calculate new values ​​, similar to the known Python list comprehensions. This code has Combinations to a list of four pairs, namely (1,3), (1,4 ), ( 2,3) and (2,4):

Val Combinations =    for {      a < - List ( 1.2 )      b < - List ( 3.4 )    Yield } (a, b ) versions

Scala 2.8

Significant new features in Release 2.8 are:

  • Revision of the Collection Library ( scala.collection )
  • Revision of the array implementation
  • Named arguments and default values ​​for arguments
  • Delimited continuations
  • Extensions for actuators concurrency
  • Provide package objects, methods, and values ​​for a package available

Scala 2.9

The version 2.9 was released on 12 May 2011. Significant innovation is the extension of the Collection to methods and classes that can perform operations in parallel ( scala.collection.parallel ). There are also numerous other improvements:

  • Improvements to the interactive console ( REPL called ) that may launch a faster, more controlled and better keyboard navigation shortcuts and decompile classes and can display types, exception conditions (exceptions) and available implicit conversions.
  • Extension of scala.sys to ways to execute instructions on the operating system shell.
  • Removal of some obsolete ( deprecated ) labeled classes and methods, such as in scala.Enumeration and clearer labeling already obsolete but not yet removed functionality, such as case- classes that inherit from other classes or case- database interface scala.dbc.

Scala 2:10

Major new features in version 2.10.0:

  • New implementation for Pattern Matching
  • Akka - actuators as a default implementation
  • Value and Implicit classes
  • String interpolation

Libraries and Frameworks

Popular frameworks for developing Web applications are backing and lift. In addition, there are many more, mostly rather minimalist solutions such Finatra or Scalatra. Frameworks from the Java world, such as Wicket or Spring can also be used.

To interact with databases it is possible through a variety of libraries, including Slick Squeryl and ScalikeJDBC. In Java, popular approaches such as the use of JPA or jOOQ, as well as the direct use of JDBC, are also possible.

For concurrent programming Scala's standard library provides an API for Futures & Promises. Implementations of the actuator model are provided, among others, Akka and Scalaz. In addition, all options of the Java standard library can be used, such as threads or java.util.concurrent. *.

Scalaz also contains plenty of other constructs that facilitate the functional programming in Scala.

Scala.js is an experimental project, compile the Scala code to JavaScript code and Scala thus make it executable in your browser.

IDE and tool support

In addition to the compiler scalac a Read- Evaluate -Print - Loop ( REPL ) is called scala available. For the IDEs Eclipse, NetBeans and IntelliJ plugins exist.

For the process of creating Scala supports, inter alia, Ant and Maven, but also provides its own tool, SBT available.

Use

Scala has found application in industry. The social networks Twitter and LinkedIn have implemented their message queues in Scala.

Another use of the language as in companies such as Novell, Siemens, Sony and EDF Trading.

Criticism

Since Scala basically code for the same JVM generated as Java and other JVM -based languages ​​, so offers no fundamental, technical advantages, provides for a review only the question of the extent resulting benefits in terms of development time, fault tolerance, and project management, as well as the quality the Scala libraries in terms of speed, accuracy and usability.

711588
de