Scala (programming language)

from Wikipedia, the free encyclopedia
Scala
Scala logo
object-oriented and functional language
Basic data
Paradigms : object-oriented , functional , imperative
Publishing year: Since 2001: internal work at EPFL
2003: Version 1
2006: Version 2
Designer: Martin Odersky
Developer: École polytechnique fédérale de Lausanne under the direction of Martin Odersky
Current  version 2.13.3   (June 25, 2020)
Typing : statically typed
Influenced by: Java , Pizza, ML , Haskell , Smalltalk , Erlang
Affected: Kotlin
Operating system : platform independent , JVM , JavaScript , LLVM (experimental)
License : Scala, similar to BSD
www.scala-lang.org

Scala is a functional and object-oriented programming language .

Concepts

Integration with Java

Scala programs can address Java JARs and vice versa. So all existing Java libraries and frameworks can be integrated into Scala projects and used there. The other way round is possible in principle, but not always problem-free in practice. The same applies to most tools: development environments such as Eclipse , NetBeans or IntelliJ also support Scala.

Object orientation

Unlike Java, Scala is a purely object-oriented programming language . Every value is an object. This also applies to primitive data types without any loss of performance , because the bytecode generated by the compiler uses primitive data types.

Interfaces are implemented using the mechanism of traits . Traits do not only consist of definitions, they can already contain concrete implementations of methods. Classes can extend one or more traits (keyword extends). This is not a question of multiple inheritance , but rather a mixin mechanism.

The keyword object(instead of class) provides an implementation of the singleton design pattern . Static fields or methods are absent from Scala, they are instead objectdefined in one .

Functional language

Functions are first-class objects . They can be used in all places where values ​​are allowed, e.g. B. Assignment to a variable (this does not mean the result of the function evaluation, but the functions themselves) or when passing parameters. Methods are not themselves first-class objects, but can be converted into functions at any time. Even higher-order functions are implemented in Scala, whereby for example currying becomes possible.

Pattern matching

An important aspect to support functional programming with Scala is pattern matching . In contrast to the switch instruction, as it is implemented in Java, for example, pattern matching works not only on the basis of values, but also in relation to the structure or type of an object. In order to be able to apply pattern matching to an instance, there must be a singleton object for it that implements the unapply method. So you can extract values ​​from the class that are derived from the fields of the class according to the unapply method. Since you often only have to extract the fields yourself, there are so-called case classes in Scala. With them, the Scala compiler automatically generates a singleton object of the same name with the apply and unapply methods, unnoticed by the programmer.

The following code implements searching in a binary search tree using pattern matching and case classes:

sealed trait Tree
case class Leaf(key: Int) extends Tree
case class Branch(key: Int, left: Tree, right: Tree) extends Tree

def contains(tree: Tree, key: Int): Boolean = tree match {
    case Leaf(i)                        => i == key
    case Branch(i, _, _) if i == key    => true
    case Branch(i, left, _) if i > key  => contains(left, key)
    case Branch(i, _, right)            => contains(right, key)
}

Example call:

val sorted: Tree = Branch(4, Leaf(2), Branch(7, Leaf(6), Leaf(8)))

println(s"contains(sorted, 4) -> ${contains(sorted, 4)}")
println(s"contains(sorted, 5) -> ${contains(sorted, 5)}")
println(s"contains(sorted, 6) -> ${contains(sorted, 6)}")

// Ausgabe:
// contains(sorted, 4) -> true
// contains(sorted, 5) -> false
// contains(sorted, 6) -> true

Closures

Functions not only access their parameters and local variables, but also variables in their context (scope), which are valid at the time of evaluation. This turns open terms into the eponymous closed terms . If the value of a variable of the context changes compared to an earlier evaluation time when the function is used multiple times, the return value and the behavior of the function can also change.

Type system

Scala is statically typed . Generic classes use types that are not yet defined at the time of development, e.g. B. List[T] Superclasses can specify abstract types that must be specified by their subclasses in the form of concrete types. The same applies to variables ( varand val) and methods.

Covariance and contravariance

Type parameters of a generic class can be provided with an annotation that determines how sub-type relations of type arguments affect the sub-type relations of generic instantiations of the class. Invariance, syntax:, K[T]means that there is no connection at all. Covariance, syntax:, K[+T]means that the relation continues in the same direction: If Tsubtype Uis of, then is K[T]subtype of K[U]. Contra-variance, syntax:, K[-T]means that the continuation takes place in the opposite direction: If Tsubtype is from U, then K[U]subtype from K[T]. Variance annotations influence at which point within the generic class the type parameter may be used: covariant type parameters, for example, may not be used as type of method arguments, contravariant not as 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 under Syntax .

Evaluation strategy

Functional expressions are strictly evaluated in Scala . However, by the key word lazythe lazy evaluation (lazy evaluation) specified by individual expressions. The collection classes also provide support with the methods viewand forcethe option of delayed evaluation. In contrast to this, the programs in Haskell are evaluated lazy by default and there are strictness annotations.

XML

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

val liste = <einkaufsliste>
                <artikel><name>Brot</name><kosten>3.50</kosten></artikel>
                <artikel><name>Apfel</name><kosten>0.29</kosten></artikel>
                <artikel><name>Eier</name><kosten>1.19</kosten></artikel>
            </einkaufsliste>
val gesamtkosten = (liste \\ "kosten").map(_.text.toDouble).sum
// Ergebnis: 4.98

Implicits

Using the modifier, methods can implicitbecome so-called implicit methods . If the compiler expects an object of a certain type A but finds an object of the incompatible type B, it searches in the lexical scope and in the companion object of A for an implicit method with which it can convert the B object into an A object . With this technique, the extension methods known from C # can be simulated (the so-called pimp my library pattern) and, within limits, even inheritance.

The last parameter list of a method can also be marked as implicit . If the parameter list is missing when a method is called, but a value marked as implicit can be found in the lexical scope, it is automatically transferred to the method. This makes it possible to simulate the type classes known from Haskell as design patterns. Scalaz, a library for purely functional programming in Scala, makes extensive use of type classes.

With implicit conversions, behavior in libraries is also implemented in Scala, which many languages cover as a special case in the compiler. For example, special rules when merging strings such as 42 + "etwas Text"or converting number types with a smaller range of values ​​to number types with a larger range of values, called string concatenation operator + or widening primitive conversions in Java .

Concurrency

While Scala supports threads through the Java class library, there is an implementation of actuators in Scala's own library . This was inspired by the actuator implementation as it was implemented in Erlang . Since Scala version 2.11, the original actuator implementation is no longer part of the standard library. It is being replaced by the Akka implementation (available from version 2.10).

In addition, the Scala standard library implements futures and parallel collections .

syntax

The syntax of the language is based on Java and ML . A number of key words and block syntax were adopted from Java, and the syntax for type annotations and declarations from ML.

Compared to Java syntax, the semicolon at the end of a line can be omitted in most cases. The syntax for the type definition of variables and return values ​​is based on that of ML instead of Java: You don't formulate Typ variable, but variable: Typ.

The declaration and definition of values, variables and methods is done using the keywords val, varand def, followed by type specifications.

val wert: Int = 42
var variable: Double = 3.14
def methode(parameter1: String, parameter2: Boolean): Unit

The compiler derives the type of a variable from the context ( type inference ). The two lines

var x = "Ein Text"

and

var x: String = "Ein Text"

are therefore equivalent.

Class and method names can use a wide variety of characters and symbols. There are z. B. identifiers like +, *, ::, \\or isEmpty_?allowed.

Method calls with no or one parameter can be noted by omitting the full stop and the opening and closing parentheses (similar to Smalltalk or Objective-C ):

5.0 + 2.0
"Test" startsWith "T"
List(1,2,3) isEmpty

corresponds

5.0.+(2.0)
"Test".startsWith("T")
List(1, 2, 3).isEmpty

With Scala it is also possible in many cases to write the source text more compactly than in Java, for example due to type inference, for comprehensions or anonymous functions.

Operators

For prefix operators, there is a fixed amount, namely +, -, ~and !. The term -xmeans the same asx.unary_-

Postfix operator expressions are also possible. There are no restrictions on the operator here, and the compilation result is a call to the (parameterless) method on the operand.

With infix operators, the first character of the operator name decides on precedence and associativity , which follows the conventions used in mathematics. The code fragment

1 + z * x

is translated to

(1).+(z.*(x))

The 1method is +called on the object and the parameter z.*(x), i.e. the result of another method call , is transferred.

If the method name of an infix operator ends with a colon, the order of receiver and parameter is reversed and the operator is right-associative:

a :: b

is translated to

b.::(a)

grind

For loops have been generalized to so-called for comprehensions to the extent that they not only combine several nested loops, but can also use any monads analogous to Haskell's Do notation .

For example, this code prints 27 lines for each value of a, b, and c.

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 list comprehensions known from Haskell . This code assigns combinationsa 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

The main innovations 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
  • Expansions for actuator concurrency
  • Package objects that provide methods and values ​​for a package

Scala 2.9

The main innovation in version 2.9 is the expansion of the collection library with methods and classes that can execute operations in parallel (scala.collection.parallel) . There are also numerous other improvements:

  • Improvements to the Interactive Console (called REPL) that may now be available. a. starts faster, has more keyboard shortcuts and better keyboard navigation, and can decompile classes and display types, exceptions and available implicit conversions.
  • Extension of scala.sys to include options for executing instructions on the shell of the operating system.
  • Removed some classes and methods marked as deprecated , such as B. in scala.Enumeration and clearer marking of already outdated but not yet removed functionality, such as As caseclasses that other caseinherit classes or database - interface scala.dbc .

Scala 2.10

Major innovations of version 2.10.0:

  • new implementation for pattern matching
  • Akka actuators as a standard implementation
  • Value and implicit classes
  • String interpolation
  • Reflection (experimental)
  • Macros (experimental)

Scala 2.11

Version 2.11.0 was published on April 17, 2014 and is more modularized than its predecessors, which means that the core standard library is smaller. In addition, detail improvements were made in the area of ​​speed and the still experimental areas of macros and reflection were improved.

Scala 2.12

Version 2.12.0 was released on November 3, 2016.

Libraries and Frameworks

Popular frameworks for developing web applications are Play and Lift . There are also many other, mostly rather minimalist solutions such as Finatra or Scalatra . Frameworks from the Java world such as Wicket or Spring can also be used.

Interacting with databases is made possible by a variety of libraries, including Slick , Squeryl, and ScalikeJDBC . Approaches popular in Java, such as the use of JPA or JOOQ , as well as the direct use of JDBC , are also possible.

Scala's standard library offers a Futures & Promises API for concurrent programming . Implementations of the actuator model are u. a. provided by Akka and Scalaz. In addition, all options of the Java standard library can be used, e.g. B. Threads or java.util.concurrent.*.

Scalaz also contains many other constructs that facilitate functional programming in Scala.

Scala.js is a project that can compile Scala code to JavaScript code and thus make Scala executable in the browser .

IDE and tool support

In addition to the compiler scalac, a Read-Evaluate-Print-Loop (REPL) named scalais available. There are plugins for the IDEs Eclipse , NetBeans and IntelliJ .

For the creation process , Scala u. a. Ant and Maven , but also provides its own tool, SBT .

use

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

The language is also used in companies such as Novell , Siemens , Sony or Électricité de France Trading .

Origin of name

The name derives from " sca lable la nguage" , and expresses that the core language very compact flavor, it provides the opportunity to voice frequently used items such. B. to implement operators or additional control structures in user classes and thereby expand the range of languages ​​and create your own domain-specific languages ( English domain-specific language , DSL ).

Examples

A Hello, World! -Program in Scala:

object HelloWorld extends App {
  println("Hello, world!")
}

A generic implementation of the quicksort algorithm with context boundaries:

def quickSort[A : Ordering](xs: List[A]): List[A] = xs match {
  case Nil     => Nil
  case y :: ys => ys partition (i => implicitly[Ordering[A]].lteq(i, y)) match {
    case (l1, l2) => quickSort(l1) ::: y :: quickSort(l2)
  }
}

history

Scala is developed in the laboratory for programming methods at the École polytechnique fédérale de Lausanne in Switzerland under the direction of Martin Odersky .

Martin Odersky worked on Modula-2 and Oberon under Niklaus Wirth . From 1995 on, he and Philip Wadler developed the pizza language , which expanded Java to include generics , function pointers and pattern matching . Later, Wadler and Odersky focused on Generic Java (GJ) on Generics for Java, this project led to the introduction of Generics in Java in 2004. From 1999 Martin Odersky worked at the École polytechnique fédérale de Lausanne , where he researched the connection between functional and object-oriented programming and developed the minimalist hybrid language Funnel . It was here in 2001 that he began developing Scala, which, unlike Funnel, was not intended to serve purely academic interests, but was designed as a full-fledged language for real applications. In spring 2004 Scala was published for the Java platform, in June 2004 for .NET .

Since the beginning of 2011, the further development of the language has been financially supported by the European Research Council . This is intended to expand the possibilities of parallel programming in particular.

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

literature

Web links

Individual evidence

  1. Release 2.13.3 . June 25, 2020 (accessed June 26, 2020).
  2. a b Pizza (programming language) in the English language Wikipedia
  3. a b Scala.js. Retrieved April 24, 2019 .
  4. ^ Scala Native. Retrieved April 24, 2019 .
  5. ^ Scala License .
  6. ^ Introduction of Scala in English on their official website
  7. Traits and Mixin Class Composition (English explanation on the Scala website)
  8. Function of a higher order (English explanation on the Scala website)
  9. Extractor Objects (English explanation on the Scala website)
  10. Case Classes (English explanation on the Scala website)
  11. Abstract types (English explanation on the Scala website)
  12. Return type (English explanation on the Scala website)
  13. Type classes (PDF)
  14. Java Language Specification, Version 3, §15.18.1, String Concatenation Operator + ( Memento from March 14, 2012 in the Internet Archive )
  15. §5.1.2, Widening Primitive Conversion ( Memento of March 29, 2012 in the Internet Archive ) in the specification of the Java language
  16. ^ The Scala Actors Migration Guide. Retrieved December 3, 2013 .
  17. Scala 2.8.0 final | The Scala Programming Language .
  18. New Collection Classes | The Scala Programming Language .
  19. Scala 2.8 Arrays | The Scala Programming Language .
  20. Named and Default Arguments | The Scala Programming Language .
  21. Scala 2.9.0 final | The Scala Programming Language .
  22. a b Read – eval – print loop in the English language Wikipedia
  23. Changelog .
  24. Scala 2.11.0 final release!
  25. Scala 2.12.0 is now available! .
  26. Futures and Promises | Scala Documentation .
  27. akka.io
  28. code.google.com
  29. ^ Scala IDE for Eclipse .
  30. ^ Scala - NetBeans Wiki .
  31. plugins.intellij.net
  32. github.com/sbt/sbt/
  33. Twitter on Scala .
  34. Index of / node / 138/159 .
  35. ^ Novell Vibe
  36. scala-lang.org
  37. Context Bounds (English explanation on the Scala website)
  38. Generic Java in the English language Wikipedia
  39. Generics in Java
  40. ^ Functional Nets .
  41. EU promotes the open source language Scala . In the heise newsticker , January 15, 2011, accessed on February 23, 2011
  42. Lightbend Inc: About Lightbend | @lightbend .