History
The design of Scala started in 2001 at thePlatforms and license
Scala runs on theOther compilers and targets
''Scala.js''Examples
"Hello World" example
TheHelloWorld2.scala
, this can be run as a script using the command:
$ scala HelloWorld2.scala
Commands can also be entered directly into the Scala interpreter, using the option :
$ scala -e 'println("Hello, World!")'
Expressions can be entered interactively in the REPL:
Basic example
The following example shows the differences between Java and Scala syntax. The function mathFunction takes an integer, squares it, and then adds the cube root of that number to the natural log of that number, returning the result (i.e., ): Some syntactic differences in this code are: * Scala does not require semicolons to end statements. * Value types are capitalized:Int, Double, Boolean
instead of int, double, boolean
.
* Parameter and return types follow, as in def
.
* Local or class variables must be preceded by val
(indicates an var
(indicates a return
operator is unnecessary in a function (although allowed); the value of the last executed statement or expression is normally the function's value.
* Instead of the Java cast operator (Type) foo
, Scala uses foo.asInstanceOfype
Peace River Airport is a municipally owned airport located west of the Town of Peace River, Alberta, Canada. The airport has one runway, which is , and a terminal building, which is .
Northern Air is based at the airport and provides scheduled ...
/code>, or a specialized function such as toDouble
or toInt
.
* Instead of Java's import foo.*;
, Scala uses import foo._
.
* Function or method foo()
can also be called as just foo
; method thread.send(signo)
can also be called as just thread send signo
; and method foo.toString()
can also be called as just foo toString
.
These syntactic relaxations are designed to allow support for domain-specific language
A domain-specific language (DSL) is a computer language specialized to a particular application domain. This is in contrast to a general-purpose language (GPL), which is broadly applicable across domains. There are a wide variety of DSLs, ranging f ...
s.
Some other basic syntactic differences:
* Array references are written like function calls, e.g. array(i)
rather than array /code>. (Internally in Scala, the former expands into array.apply(i) which returns the reference)
* Generic types are written as e.g. Listtring
Tring is a market town and civil parish in the Borough of Dacorum, Hertfordshire, England. It is situated in a gap passing through the Chiltern Hills, classed as an Area of Outstanding Natural Beauty, from Central London. Tring is linked to ...
/code> rather than Java's List<String>
.
* Instead of the pseudo-type void
, Scala has the actual singleton class Unit
(see below).
Example with classes
The following example contrasts the definition of classes in Java and Scala.
The code above shows some of the conceptual differences between Java and Scala's handling of classes:
* Scala has no static variables or methods. Instead, it has ''singleton objects'', which are essentially classes with only one instance. Singleton objects are declared using object
instead of class
. It is common to place static variables and methods in a singleton object with the same name as the class name, which is then known as a ''companion object''. (The underlying class for the singleton object has a $
appended. Hence, for class Foo
with companion object object Foo
, under the hood there's a class Foo$
containing the companion object's code, and one object of this class is created, using the singleton pattern
In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to a singular instance. One of the well-known "Gang of Four" design patterns, which describe how to solve recurring problems ...
.)
* In place of constructor parameters, Scala has ''class parameters'', which are placed on the class, similar to parameters to a function. When declared with a val
or var
modifier, fields are also defined with the same name, and automatically initialized from the class parameters. (Under the hood, external access to public fields always goes through accessor (getter) and mutator (setter) methods, which are automatically created. The accessor function has the same name as the field, which is why it's unnecessary in the above example to explicitly declare accessor methods.) Note that alternative constructors can also be declared, as in Java. Code that would go into the default constructor In computer programming languages, the term default constructor can refer to a constructor that is automatically generated by the compiler in the absence of any programmer-defined constructors (e.g. in Java), and is usually a nullary constructor. I ...
(other than initializing the member variables) goes directly at class level.
* Default visibility in Scala is public
.
Features (with reference to Java)
Scala has the same compiling model as Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
and C#, namely separate compiling and dynamic class loading, so that Scala code can call Java libraries.
Scala's operational characteristics are the same as Java's. The Scala compiler generates byte code that is nearly identical to that generated by the Java compiler. In fact, Scala code can be decompiled
A decompiler is a computer program that translates an executable file to a high-level source file which can be recompiled successfully. It does therefore the opposite of a typical compiler, which translates a high-level language to a low-level la ...
to readable Java code, with the exception of certain constructor operations. To the Java virtual machine
A Java virtual machine (JVM) is a virtual machine that enables a computer to run Java programs as well as programs written in other languages that are also compiled to Java bytecode. The JVM is detailed by a specification that formally describes ...
(JVM), Scala code and Java code are indistinguishable. The only difference is one extra runtime library, scala-library.jar
.
Scala adds a large number of features compared with Java, and has some fundamental differences in its underlying model of expressions and types, which make the language theoretically cleaner and eliminate several ''corner cases
In engineering, a corner case (or pathological case) involves a problem or situation that occurs only outside normal operating parameters—specifically one that manifests itself when multiple environmental variables or conditions are simultaneou ...
'' in Java. From the Scala perspective, this is practically important because several added features in Scala are also available in C#.
Syntactic flexibility
As mentioned above, Scala has a good deal of syntactic flexibility, compared with Java. The following are some examples:
* Semicolons are unnecessary; lines are automatically joined if they begin or end with a token that cannot normally come in this position, or if there are unclosed parentheses or brackets.
* Any method can be used as an infix operator, e.g. "%d apples".format(num)
and "%d apples" format num
are equivalent. In fact, arithmetic operators like +
and <<
are treated just like any other methods, since function names are allowed to consist of sequences of arbitrary symbols (with a few exceptions made for things like parens, brackets and braces that must be handled specially); the only special treatment that such symbol-named methods undergo concerns the handling of precedence.
* Methods apply
and update
have syntactic short forms. foo()
—where foo
is a value (singleton object or class instance)—is short for foo.apply()
, and foo() = 42
is short for foo.update(42)
. Similarly, foo(42)
is short for foo.apply(42)
, and foo(4) = 2
is short for foo.update(4, 2)
. This is used for collection classes and extends to many other cases, such as STM cells.
* Scala distinguishes between no-parens (def foo = 42
) and empty-parens (def foo() = 42
) methods. When calling an empty-parens method, the parentheses may be omitted, which is useful when calling into Java libraries that do not know this distinction, e.g., using foo.toString
instead of foo.toString()
. By convention, a method should be defined with empty-parens when it performs side effects
In medicine, a side effect is an effect, whether therapeutic or adverse, that is secondary to the one intended; although the term is predominantly employed to describe adverse effects, it can also apply to beneficial, but unintended, consequence ...
.
* Method names ending in colon (:
) expect the argument on the left-hand-side and the receiver on the right-hand-side. For example, the 4 :: 2 :: Nil
is the same as Nil.::(2).::(4)
, the first form corresponding visually to the result (a list with first element 4 and second element 2).
* Class body variables can be transparently implemented as separate getter and setter methods. For trait FooLike
, an implementation may be . The call site will still be able to use a concise foo.bar = 42
.
* The use of curly braces instead of parentheses is allowed in method calls. This allows pure library implementations of new control structures. For example, breakable
looks as if breakable
was a language defined keyword, but really is just a method taking a thunk
In computer programming, a thunk is a subroutine used to inject a calculation into another subroutine. Thunks are primarily used to delay a calculation until its result is needed, or to insert operations at the beginning or end of the other subro ...
argument. Methods that take thunks or functions often place these in a second parameter list, allowing to mix parentheses and curly braces syntax: Vector.fill(4)
is the same as Vector.fill(4)(math.random)
. The curly braces variant allows the expression to span multiple lines.
*For-expressions (explained further down) can accommodate any type that defines monadic methods such as map
, flatMap
and filter
.
By themselves, these may seem like questionable choices, but collectively they serve the purpose of allowing domain-specific language
A domain-specific language (DSL) is a computer language specialized to a particular application domain. This is in contrast to a general-purpose language (GPL), which is broadly applicable across domains. There are a wide variety of DSLs, ranging f ...
s to be defined in Scala without needing to extend the compiler. For example, Erlang's special syntax for sending a message to an actor, i.e. actor ! message
can be (and is) implemented in a Scala library without needing language extensions.
Unified type system
Java makes a sharp distinction between primitive types (e.g. int
and boolean
) and reference types (any class
Class or The Class may refer to:
Common uses not otherwise categorized
* Class (biology), a taxonomic rank
* Class (knowledge representation), a collection of individuals or objects
* Class (philosophy), an analytical concept used differentl ...
). Only reference types are part of the inheritance scheme, deriving from java.lang.Object
. In Scala, all types inherit from a top-level class Any
, whose immediate children are AnyVal
(value types, such as Int
and Boolean
) and AnyRef
(reference types, as in Java). This means that the Java distinction between primitive types and boxed types (e.g. int
vs. Integer
) is not present in Scala; boxing
Boxing (also known as "Western boxing" or "pugilism") is a combat sport in which two people, usually wearing protective gloves and other protective equipment such as hand wraps and mouthguards, throw punches at each other for a predetermined ...
and unboxing is completely transparent to the user. Scala 2.10 allows for new value types to be defined by the user.
For-expressions
Instead of the Java "foreach
In computer programming, foreach loop (or for each loop) is a control flow statement for traversing items in a collection. is usually used in place of a standard loop statement. Unlike other loop constructs, however, loops usually maintain ...
" loops for looping through an iterator, Scala has for
-expressions, which are similar to list comprehension
A list comprehension is a Syntax of programming languages, syntactic construct available in some programming languages for creating a list based on existing list (computing), lists. It follows the form of the mathematical ''set-builder notation'' ( ...
s in languages such as Haskell, or a combination of list comprehensions and generator expressions in Python
Python may refer to:
Snakes
* Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia
** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia
* Python (mythology), a mythical serpent
Computing
* Python (pro ...
. For-expressions using the yield
keyword allow a new collection
Collection or Collections may refer to:
* Cash collection, the function of an accounts receivable department
* Collection (church), money donated by the congregation during a church service
* Collection agency, agency to collect cash
* Collectio ...
to be generated by iterating over an existing one, returning a new collection of the same type. They are translated by the compiler into a series of map
, flatMap
and filter
calls. Where yield
is not used, the code approximates to an imperative-style loop, by translating to foreach
.
A simple example is:
val s = for (x <- 1 to 25 if x*x > 50) yield 2*x
The result of running it is the following vector:
:Vector(16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50)
(Note that the expression 1 to 25
is not special syntax. The method to
is rather defined in the standard Scala library as an extension method on integers, using a technique known as implicit conversions that allows new methods to be added to existing types.)
A more complex example of iterating over a map is:
// Given a map specifying Twitter users mentioned in a set of tweets,
// and number of times each user was mentioned, look up the users
// in a map of known politicians, and return a new map giving only the
// Democratic politicians (as objects, rather than strings).
val dem_mentions = for yield (account, times)
Expression (mention, times) <- mentions
is an example of pattern matching
In computer science, pattern matching is the act of checking a given sequence of tokens for the presence of the constituents of some pattern. In contrast to pattern recognition, the match usually has to be exact: "either it will or will not be ...
(see below). Iterating over a map returns a set of key-value tuple
In mathematics, a tuple is a finite ordered list (sequence) of elements. An -tuple is a sequence (or ordered list) of elements, where is a non-negative integer. There is only one 0-tuple, referred to as ''the empty tuple''. An -tuple is defi ...
s, and pattern-matching allows the tuples to easily be destructured into separate variables for the key and value. Similarly, the result of the comprehension also returns key-value tuples, which are automatically built back up into a map because the source object (from the variable mentions
) is a map. Note that if mentions
instead held a list, set, array or other collection of tuples, exactly the same code above would yield a new collection of the same type.
Functional tendencies
While supporting all of the object-oriented features available in Java (and in fact, augmenting them in various ways), Scala also provides a large number of capabilities that are normally found only in functional programming
In computer science, functional programming is a programming paradigm where programs are constructed by Function application, applying and Function composition (computer science), composing Function (computer science), functions. It is a declar ...
languages. Together, these features allow Scala programs to be written in an almost completely functional style and also allow functional and object-oriented styles to be mixed.
Examples are:
* No distinction between statements and expressions
* Type inference
Type inference refers to the automatic detection of the type of an expression in a formal language. These include programming languages and mathematical type systems, but also natural languages in some branches of computer science and linguistics ...
* Anonymous function
In computer programming, an anonymous function (function literal, lambda abstraction, lambda function, lambda expression or block) is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed to ...
s with capturing semantics (i.e., closures)
*Immutable variables and objects
* Lazy evaluation
In programming language theory, lazy evaluation, or call-by-need, is an evaluation strategy which delays the evaluation of an expression until its value is needed (non-strict evaluation) and which also avoids repeated evaluations (sharing).
The b ...
* Delimited continuation In programming languages, a delimited continuation, composable continuation or partial continuation, is a "slice" of a continuation frame that has been reified into a function. Unlike regular continuations, delimited continuations return a value, a ...
s (since 2.8)
* Higher-order function
In mathematics and computer science, a higher-order function (HOF) is a function that does at least one of the following:
* takes one or more functions as arguments (i.e. a procedural parameter, which is a parameter of a procedure that is itself ...
s
* Nested functions
* Currying
In mathematics and computer science, currying is the technique of translating the evaluation of a function that takes multiple arguments into evaluating a sequence of functions, each with a single argument. For example, currying a function f that ...
* Pattern matching
In computer science, pattern matching is the act of checking a given sequence of tokens for the presence of the constituents of some pattern. In contrast to pattern recognition, the match usually has to be exact: "either it will or will not be ...
* Algebraic data types
In computer programming, especially functional programming and type theory, an algebraic data type (ADT) is a kind of composite type, i.e., a type formed by combining other types.
Two common classes of algebraic types are product types (i.e., t ...
(through ''case classes'')
* Tuples
In mathematics, a tuple is a finite ordered list (sequence) of elements. An -tuple is a sequence (or ordered list) of elements, where is a non-negative integer. There is only one 0-tuple, referred to as ''the empty tuple''. An -tuple is defi ...
Everything is an expression
Unlike C or Java, but similar to languages such as Lisp
A lisp is a speech impairment in which a person misarticulates sibilants (, , , , , , , ). These misarticulations often result in unclear speech.
Types
* A frontal lisp occurs when the tongue is placed anterior to the target. Interdental lisping ...
, Scala makes no distinction between statements and expressions. All statements are in fact expressions that evaluate to some value. Functions that would be declared as returning void
in C or Java, and statements like while
that logically do not return a value, are in Scala considered to return the type Unit
, which is a singleton type, with only one object of that type. Functions and operators that never return at all (e.g. the throw
operator or a function that always exits non-locally using an exception) logically have return type Nothing
, a special type containing no objects; that is, a bottom type
In type theory, a theory within mathematical logic, the bottom type of a type system is the type that is a subtype of all other types.
Where such a type exists, it is often represented with the up tack (⊥) symbol.
When the bottom type is empty, ...
, i.e. a subclass of every possible type. (This in turn makes type Nothing
compatible with every type, allowing type inference
Type inference refers to the automatic detection of the type of an expression in a formal language. These include programming languages and mathematical type systems, but also natural languages in some branches of computer science and linguistics ...
to function correctly.)
Similarly, an if-then-else
"statement" is actually an expression, which produces a value, i.e. the result of evaluating one of the two branches. This means that such a block of code can be inserted wherever an expression is desired, obviating the need for a ternary operator
In mathematics, a ternary operation is an ''n''- ary operation with ''n'' = 3. A ternary operation on a set ''A'' takes any given three elements of ''A'' and combines them to form a single element of ''A''.
In computer science, a ternary operator ...
in Scala:
For similar reasons, return
statements are unnecessary in Scala, and in fact are discouraged. As in Lisp, the last expression in a block of code is the value of that block of code, and if the block of code is the body of a function, it will be returned by the function.
To make it clear that all functions are expressions, even methods that return Unit
are written with an equals sign
def printValue(x: String): Unit =
or equivalently (with type inference, and omitting the unnecessary braces):
def printValue(x: String) = println("I ate a %s" format x)
Type inference
Due to type inference
Type inference refers to the automatic detection of the type of an expression in a formal language. These include programming languages and mathematical type systems, but also natural languages in some branches of computer science and linguistics ...
, the type of variables, function return values, and many other expressions can typically be omitted, as the compiler can deduce it. Examples are val x = "foo"
(for an immutable constant or immutable object
In object-oriented and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created.Goetz et al. ''Java Concurrency in Practice''. Addison Wesley Professional, 2006, Section 3.4 ...
) or var x = 1.5
(for a variable whose value can later be changed). Type inference in Scala is essentially local, in contrast to the more global Hindley-Milner algorithm used in Haskell
Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lang ...
, ML and other more purely functional languages. This is done to facilitate object-oriented programming. The result is that certain types still need to be declared (most notably, function parameters, and the return types of recursive functions), e.g.
def formatApples(x: Int) = "I ate %d apples".format(x)
or (with a return type declared for a recursive function)
def factorial(x: Int): Int =
if (x 0)
1
else
x*factorial(x - 1)
Anonymous functions
In Scala, functions are objects, and a convenient syntax exists for specifying anonymous function
In computer programming, an anonymous function (function literal, lambda abstraction, lambda function, lambda expression or block) is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed to ...
s. An example is the expression x => x < 2
, which specifies a function with one parameter, that compares its argument to see if it is less than 2. It is equivalent to the Lisp form (lambda (x) (< x 2))
. Note that neither the type of x
nor the return type need be explicitly specified, and can generally be inferred by type inference
Type inference refers to the automatic detection of the type of an expression in a formal language. These include programming languages and mathematical type systems, but also natural languages in some branches of computer science and linguistics ...
; but they can be explicitly specified, e.g. as (x: Int) => x < 2
or even (x: Int) => (x < 2): Boolean
.
Anonymous functions behave as true closures in that they automatically capture any variables that are lexically available in the environment of the enclosing function. Those variables will be available even after the enclosing function returns, and unlike in the case of Java's ''anonymous inner classes'' do not need to be declared as final. (It is even possible to modify such variables if they are mutable, and the modified value will be available the next time the anonymous function is called.)
An even shorter form of anonymous function uses placeholder
Placeholder may refer to:
Language
* Placeholder name, a term or terms referring to something or somebody whose name is not known or, in that particular context, is not significant or relevant.
* Filler text, text generated to fill space or provi ...
variables: For example, the following:
:list map
can be written more concisely as
:list map
or even
:list map sqrt
Immutability
Scala enforces a distinction between immutable and mutable variables. Mutable variables are declared using the var
keyword and immutable values are declared using the val
keyword.
A variable declared using the val
keyword cannot be reassigned in the same way that a variable declared using the final
keyword can't be reassigned in Java. val
s are only shallowly immutable, that is, an object referenced by a val is not guaranteed to itself be immutable.
Immutable classes are encouraged by convention however, and the Scala standard library provides a rich set of immutable collection
Collection or Collections may refer to:
* Cash collection, the function of an accounts receivable department
* Collection (church), money donated by the congregation during a church service
* Collection agency, agency to collect cash
* Collectio ...
classes.
Scala provides mutable and immutable variants of most collection classes, and the immutable version is always used unless the mutable version is explicitly imported.
The immutable variants are persistent data structure
In computing, a persistent data structure or not ephemeral data structure is a data structure that always preserves the previous version of itself when it is modified. Such data structures are effectively immutable, as their operations do not (v ...
s that always return an updated copy of an old object instead of updating the old object destructively in place.
An example of this is immutable linked lists where prepending an element to a list is done by returning a new list node consisting of the element and a reference to the list tail.
Appending an element to a list can only be done by prepending all elements in the old list to a new list with only the new element.
In the same way, inserting an element in the middle of a list will copy the first half of the list, but keep a reference to the second half of the list. This is called structural sharing.
This allows for very easy concurrency — no locks are needed as no shared objects are ever modified.
Lazy (non-strict) evaluation
Evaluation is strict ("eager") by default. In other words, Scala evaluates expressions as soon as they are available, rather than as needed. However, it is possible to declare a variable non-strict ("lazy") with the lazy
keyword, meaning that the code to produce the variable's value will not be evaluated until the first time the variable is referenced. Non-strict collections of various types also exist (such as the type Stream
, a non-strict linked list), and any collection can be made non-strict with the view
method. Non-strict collections provide a good semantic fit to things like server-produced data, where the evaluation of the code to generate later elements of a list (that in turn triggers a request to a server, possibly located somewhere else on the web) only happens when the elements are actually needed.
Tail recursion
Functional programming languages commonly provide tail call
In computer science, a tail call is a subroutine call performed as the final action of a procedure. If the target of a tail is the same subroutine, the subroutine is said to be tail recursive, which is a special case of direct recursion. Tail recur ...
optimization to allow for extensive use of recursion
Recursion (adjective: ''recursive'') occurs when a thing is defined in terms of itself or of its type. Recursion is used in a variety of disciplines ranging from linguistics to logic. The most common application of recursion is in mathematics ...
without stack overflow
In software, a stack overflow occurs if the call stack pointer exceeds the stack bound. The call stack may consist of a limited amount of address space, often determined at the start of the program. The size of the call stack depends on many fac ...
problems. Limitations in Java bytecode complicate tail call optimization on the JVM. In general, a function that calls itself with a tail call can be optimized, but mutually recursive functions cannot. Trampoline
A trampoline is a device consisting of a piece of taut, strong fabric stretched between a steel frame using many coiled spring (device), springs. Not all trampolines have springs, as the Springfree Trampoline uses glass-reinforced plastic rods. ...
s have been suggested as a workaround. Trampoline support has been provided by the Scala library with the object scala.util.control.TailCalls
since Scala 2.8.0 (released 14 July 2010). A function may optionally be annotated with @tailrec
, in which case it will not compile unless it is tail recursive.
Case classes and pattern matching
Scala has built-in support for pattern matching
In computer science, pattern matching is the act of checking a given sequence of tokens for the presence of the constituents of some pattern. In contrast to pattern recognition, the match usually has to be exact: "either it will or will not be ...
, which can be thought of as a more sophisticated, extensible version of a switch statement
In computer programming languages, a switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map.
Switch statements function some ...
, where arbitrary data types can be matched (rather than just simple types like integers, booleans and strings), including arbitrary nesting. A special type of class known as a ''case class'' is provided, which includes automatic support for pattern matching and can be used to model the algebraic data type
In computer programming, especially functional programming and type theory, an algebraic data type (ADT) is a kind of composite type, i.e., a type formed by combining other types.
Two common classes of algebraic types are product types (i.e., t ...
s used in many functional programming languages. (From the perspective of Scala, a case class is simply a normal class for which the compiler automatically adds certain behaviors that could also be provided manually, e.g., definitions of methods providing for deep comparisons and hashing, and destructuring a case class on its constructor parameters during pattern matching.)
An example of a definition of the quicksort
Quicksort is an efficient, general-purpose sorting algorithm. Quicksort was developed by British computer scientist Tony Hoare in 1959 and published in 1961, it is still a commonly used algorithm for sorting. Overall, it is slightly faster than ...
algorithm using pattern matching is this:
def qsort(list: List nt: List nt= list match
The idea here is that we partition a list into the elements less than a pivot and the elements not less, recursively sort each part, and paste the results together with the pivot in between. This uses the same divide-and-conquer strategy of mergesort
In computer science, merge sort (also commonly spelled as mergesort) is an efficient, general-purpose, and comparison-based sorting algorithm. Most implementations produce a stable sort, which means that the order of equal elements is the same i ...
and other fast sorting algorithms.
The match
operator is used to do pattern matching on the object stored in list
. Each case
expression is tried in turn to see if it will match, and the first match determines the result. In this case, Nil
only matches the literal object Nil
, but pivot :: tail
matches a non-empty list, and simultaneously ''destructures'' the list according to the pattern given. In this case, the associated code will have access to a local variable named pivot
holding the head of the list, and another variable tail
holding the tail of the list. Note that these variables are read-only, and are semantically very similar to variable bindings established using the let
operator in Lisp and Scheme.
Pattern matching also happens in local variable declarations. In this case, the return value of the call to tail.partition
is a tuple
In mathematics, a tuple is a finite ordered list (sequence) of elements. An -tuple is a sequence (or ordered list) of elements, where is a non-negative integer. There is only one 0-tuple, referred to as ''the empty tuple''. An -tuple is defi ...
— in this case, two lists. (Tuples differ from other types of containers, e.g. lists, in that they are always of fixed size and the elements can be of differing types — although here they are both the same.) Pattern matching is the easiest way of fetching the two parts of the tuple.
The form _ < pivot
is a declaration of an anonymous function
In computer programming, an anonymous function (function literal, lambda abstraction, lambda function, lambda expression or block) is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed to ...
with a placeholder variable; see the section above on anonymous functions.
The list operators ::
(which adds an element onto the beginning of a list, similar to cons
in Lisp and Scheme) and :::
(which appends two lists together, similar to append
in Lisp and Scheme) both appear. Despite appearances, there is nothing "built-in" about either of these operators. As specified above, any string of symbols can serve as function name, and a method applied to an object can be written "infix
An infix is an affix inserted inside a word stem (an existing word or the core of a family of words). It contrasts with ''adfix,'' a rare term for an affix attached to the outside of a stem, such as a prefix or suffix.
When marking text for int ...
"-style without the period or parentheses. The line above as written:
::qsort(smaller) ::: pivot :: qsort(rest)
could also be written thus:
::qsort(rest).::(pivot).:::(qsort(smaller))
in more standard method-call notation. (Methods that end with a colon are right-associative and bind to the object to the right.)
Partial functions
In the pattern-matching example above, the body of the match
operator is a partial function
In mathematics, a partial function from a set to a set is a function from a subset of (possibly itself) to . The subset , that is, the domain of viewed as a function, is called the domain of definition of . If equals , that is, if is de ...
, which consists of a series of case
expressions, with the first matching expression prevailing, similar to the body of a switch statement
In computer programming languages, a switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map.
Switch statements function some ...
. Partial functions are also used in the exception-handling portion of a try
statement:
try catch
Finally, a partial function can be used alone, and the result of calling it is equivalent to doing a match
over it. For example, the prior code for quicksort
Quicksort is an efficient, general-purpose sorting algorithm. Quicksort was developed by British computer scientist Tony Hoare in 1959 and published in 1961, it is still a commonly used algorithm for sorting. Overall, it is slightly faster than ...
can be written thus:
val qsort: List nt=> List nt=
Here a read-only ''variable'' is declared whose type is a function from lists of integers to lists of integers, and bind it to a partial function. (Note that the single parameter of the partial function is never explicitly declared or named.) However, we can still call this variable exactly as if it were a normal function:
scala> qsort(List(6,2,5,9))
res32: List nt= List(2, 5, 6, 9)
Object-oriented extensions
Scala is a pure object-oriented language
Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of pro ...
in the sense that every value is an object
Object may refer to:
General meanings
* Object (philosophy), a thing, being, or concept
** Object (abstract), an object which does not exist at any particular time or place
** Physical object, an identifiable collection of matter
* Goal, an ai ...
. Data type
In computer science and computer programming, a data type (or simply type) is a set of possible values and a set of allowed operations on it. A data type tells the compiler or interpreter how the programmer intends to use the data. Most progra ...
s and behaviors of objects are described by classes and traits. Class abstractions are extended by subclassing and by a flexible mixin
In object-oriented programming languages, a mixin (or mix-in) is a class that contains methods for use by other classes without having to be the parent class of those other classes. How those other classes gain access to the mixin's methods depend ...
-based composition mechanism to avoid the problems of multiple inheritance
Multiple inheritance is a feature of some object-oriented computer programming languages in which an object or class can inherit features from more than one parent object or parent class. It is distinct from single inheritance, where an object or ...
.
Traits are Scala's replacement for Java's interfaces
Interface or interfacing may refer to:
Academic journals
* Interface (journal), ''Interface'' (journal), by the Electrochemical Society
* ''Interface, Journal of Applied Linguistics'', now merged with ''ITL International Journal of Applied Lin ...
. Interfaces in Java versions under 8 are highly restricted, able only to contain abstract function declarations. This has led to criticism that providing convenience methods in interfaces is awkward (the same methods must be reimplemented in every implementation), and extending a published interface in a backwards-compatible way is impossible. Traits are similar to mixin
In object-oriented programming languages, a mixin (or mix-in) is a class that contains methods for use by other classes without having to be the parent class of those other classes. How those other classes gain access to the mixin's methods depend ...
classes in that they have nearly all the power of a regular abstract class, lacking only class parameters (Scala's equivalent to Java's constructor parameters), since traits are always mixed in with a class. The super
operator behaves specially in traits, allowing traits to be chained using composition in addition to inheritance. The following example is a simple window system:
abstract class Window
class SimpleWindow extends Window
trait WindowDecoration extends Window
trait HorizontalScrollbarDecoration extends WindowDecoration
trait VerticalScrollbarDecoration extends WindowDecoration
trait TitleDecoration extends WindowDecoration
A variable may be declared thus:
val mywin = new SimpleWindow with VerticalScrollbarDecoration with HorizontalScrollbarDecoration with TitleDecoration
The result of calling mywin.draw()
is:
in TitleDecoration
in HorizontalScrollbarDecoration
in VerticalScrollbarDecoration
in SimpleWindow
In other words, the call to draw
first executed the code in TitleDecoration
(the last trait mixed in), then (through the super()
calls) threaded back through the other mixed-in traits and eventually to the code in Window
, ''even though none of the traits inherited from one another''. This is similar to the decorator pattern
In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, dynamically, without affecting the behavior of other objects from the same class. The decorator pattern is often ...
, but is more concise and less error-prone, as it doesn't require explicitly encapsulating the parent window, explicitly forwarding functions whose implementation isn't changed, or relying on run-time initialization of entity relationships. In other languages, a similar effect could be achieved at compile-time with a long linear chain of implementation inheritance
In object-oriented programming, inheritance is the mechanism of basing an object or class upon another object ( prototype-based inheritance) or class ( class-based inheritance), retaining similar implementation. Also defined as deriving new classe ...
, but with the disadvantage compared to Scala that one linear inheritance chain would have to be declared for each possible combination of the mix-ins.
Expressive type system
Scala is equipped with an expressive static type system that mostly enforces the safe and coherent use of abstractions. The type system is, however, not sound
In physics, sound is a vibration that propagates as an acoustic wave, through a transmission medium such as a gas, liquid or solid.
In human physiology and psychology, sound is the ''reception'' of such waves and their ''perception'' by the ...
. In particular, the type system supports:
* Classes and abstract type
In programming languages, an abstract type is a type in a nominative type system that cannot be instantiated directly; a type that is not abstract – which ''can'' be instantiated – is called a ''concrete type''. Every instance of an abstrac ...
s as object members
* Structural types
* Path-dependent types
* Compound types
* Explicitly typed self references
* Generic classes
* Polymorphic methods
* Upper and lower type bounds
* Variance
In probability theory and statistics, variance is the expectation of the squared deviation of a random variable from its population mean or sample mean. Variance is a measure of dispersion, meaning it is a measure of how far a set of numbers ...
* Annotation
An annotation is extra information associated with a particular point in a document or other piece of information. It can be a note that includes a comment or explanation. Annotations are sometimes presented in the margin of book pages. For anno ...
* Views
Scala is able to infer types by use. This makes most static type declarations optional. Static types need not be explicitly declared unless a compiler error indicates the need. In practice, some static type declarations are included for the sake of code clarity.
Type enrichment
A common technique in Scala, known as "enrich my library" (originally termed " pimp my library" by Martin Odersky in 2006; concerns were raised about this phrasing due to its negative connotations and immaturity), allows new methods to be used as if they were added to existing types. This is similar to the C# concept of extension method
In object-oriented computer programming, an extension method is a method added to an object after the original object was compiled. The modified object is often a class, a prototype or a type. Extension methods are features of some object-orie ...
s but more powerful, because the technique is not limited to adding methods and can, for instance, be used to implement new interfaces. In Scala, this technique involves declaring an implicit conversion
In computer science, type conversion, type casting, type coercion, and type juggling are different ways of changing an expression from one data type to another. An example would be the conversion of an integer value into a floating point valu ...
from the type "receiving" the method to a new type (typically, a class) that wraps the original type and provides the additional method. If a method cannot be found for a given type, the compiler automatically searches for any applicable implicit conversions to types that provide the method in question.
This technique allows new methods to be added to an existing class using an add-on library such that only code that ''imports'' the add-on library gets the new functionality, and all other code is unaffected.
The following example shows the enrichment of type Int
with methods isEven
and isOdd
:
object MyExtensions
import MyExtensions._ // bring implicit enrichment into scope
4.isEven // -> true
Importing the members of MyExtensions
brings the implicit conversion to extension class IntPredicates
into scope.
Concurrency
Scala's standard library includes support for futures and promises
In computer science, future, promise, delay, and deferred refer to constructs used for synchronizing program execution in some concurrent programming languages. They describe an object that acts as a proxy for a result that is initially unknown ...
, in addition to the standard Java concurrency APIs. Originally, it also included support for the actor model
The actor model in computer science is a mathematical model of concurrent computation that treats ''actor'' as the universal primitive of concurrent computation. In response to a message it receives, an actor can: make local decisions, create more ...
, which is now available as a separate open source platform Akka
Akka or AKKA may refer to:
Arts and entertainment
* ''Akka'' (film), a 1976 Indian Tamil film
* ''Akka'' (TV series), a 2014–2015 Indian Tamil soap opera
* Akka, a character in the children's novel ''The Wonderful Adventures of Nils'' by Selma ...
What is Akka?
Akka online documentation created by Lightbend Inc. Akka actors may be distributed Distribution may refer to:
Mathematics
*Distribution (mathematics), generalized functions used to formulate solutions of partial differential equations
*Probability distribution, the probability of a particular value or value range of a varia ...
or combined with software transactional memory In computer science, software transactional memory (STM) is a concurrency control mechanism analogous to database transactions for controlling access to shared memory in concurrent computing. It is an alternative to lock-based synchronization. STM ...
(''transactors''). Alternative communicating sequential processes
In computer science, communicating sequential processes (CSP) is a formal language for describing patterns of interaction in concurrent systems. It is a member of the family of mathematical theories of concurrency known as process algebras, or pro ...
(CSP) implementations for channel-based message passing are Communicating Scala Objects, or simply via JCSP.
An Actor is like a thread instance with a mailbox. It can be created by system.actorOf
, overriding the receive
method to receive messages and using the !
(exclamation point) method to send a message.
The following example shows an EchoServer that can receive messages and then print them.
val echoServer = actor(new Act )
echoServer ! "hi"
Scala also comes with built-in support for data-parallel programming in the form of Parallel Collections integrated into its Standard Library since version 2.9.0.
The following example shows how to use Parallel Collections to improve performance.
val urls = List("https://scala-lang.org", "https://github.com/scala/scala")
def fromURL(url: String) = scala.io.Source.fromURL(url)
.getLines().mkString("\n")
val t = System.currentTimeMillis()
urls.par.map(fromURL(_)) // par returns parallel implementation of a collection
println("time: " + (System.currentTimeMillis - t) + "ms")
Besides futures and promises, actor support, and data parallelism
Data parallelism is parallelization across multiple processors in parallel computing environments. It focuses on distributing the data across different nodes, which operate on the data in parallel. It can be applied on regular data structures like ...
, Scala also supports asynchronous programming with software transactional memory, and event streams.
Cluster computing
The most well-known open-source cluster-computing solution written in Scala is Apache Spark
Apache Spark is an open-source unified analytics engine for large-scale data processing. Spark provides an interface for programming clusters with implicit data parallelism and fault tolerance. Originally developed at the University of Californi ...
. Additionally, Apache Kafka
Apache Kafka is a distributed event store and stream-processing platform. It is an open-source system developed by the Apache Software Foundation written in Java and Scala. The project aims to provide a unified, high-throughput, low-latency plat ...
, the publish–subscribe message queue
In computer science, message queues and mailboxes are software-engineering components typically used for inter-process communication (IPC), or for inter- thread communication within the same process. They use a queue for messaging – the ...
popular with Spark and other stream processing technologies, is written in Scala.
Testing
There are several ways to test code in Scala. ScalaTest supports multiple testing styles and can integrate with Java-based testing frameworks. ScalaCheck is a library similar to Haskell's QuickCheck
QuickCheck is a software library, specifically a combinator library, originally written in the programming language Haskell, designed to assist in software testing by generating test cases for test suites – an approach known as property testi ...
. specs2 is a library for writing executable software specifications. ScalaMock provides support for testing high-order and curried functions. JUnit
JUnit is a unit testing framework for the Java programming language. JUnit has been important in the development of test-driven development, and is one of a family of unit testing frameworks which is collectively known as xUnit that originated w ...
and TestNG
TestNG is a testing framework for the Java programming language created by Cédric Beust and inspired by JUnit and NUnit. The design goal of TestNG is to cover a wider range of test categories: unit, functional, end-to-end, integration, etc., wit ...
are popular testing frameworks written in Java.
Versions
Comparison with other JVM languages
Scala is often compared with Groovy
''Groovy'' (or, less commonly, ''groovie'' or ''groovey'') is a slang colloquialism popular during the 1950s, '60s and '70s. It is roughly synonymous with words such as "excellent", "fashionable", or "amazing", depending on context.
History
The ...
and Clojure
Clojure (, like ''closure'') is a dynamic and functional dialect of the Lisp programming language on the Java platform. Like other Lisp dialects, Clojure treats code as data and has a Lisp macro system. The current development process is comm ...
, two other programming languages also using the JVM. Substantial differences between these languages exist in the type system, in the extent to which each language supports object-oriented and functional programming, and in the similarity of their syntax to that of Java.
Scala is statically typed
In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a type to every "term" (a word, phrase, or other set of symbols). Usually the terms are various constructs of a computer progra ...
, while both Groovy and Clojure are dynamically typed
In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a type to every "term" (a word, phrase, or other set of symbols). Usually the terms are various constructs of a computer progra ...
. This makes the type system more complex and difficult to understand but allows almost all type errors to be caught at compile-time and can result in significantly faster execution. By contrast, dynamic typing requires more testing to ensure program correctness, and thus is generally slower, to allow greater programming flexibility and simplicity. Regarding speed differences, current versions of Groovy and Clojure allow optional type annotations to help programs avoid the overhead of dynamic typing in cases where types are practically static. This overhead is further reduced when using recent versions of the JVM, which has been enhanced with an ''invoke dynamic'' instruction for methods that are defined with dynamically typed arguments. These advances reduce the speed gap between static and dynamic typing, although a statically typed language, like Scala, is still the preferred choice when execution efficiency is very important.
Regarding programming paradigms, Scala inherits the object-oriented model of Java and extends it in various ways. Groovy, while also strongly object-oriented, is more focused in reducing verbosity. In Clojure, object-oriented programming is deemphasised with functional programming being the main strength of the language. Scala also has many functional programming facilities, including features found in advanced functional languages like Haskell
Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lang ...
, and tries to be agnostic between the two paradigms, letting the developer choose between the two paradigms or, more frequently, some combination thereof.
Regarding syntax similarity with Java, Scala inherits much of Java's syntax, as is the case with Groovy. Clojure on the other hand follows the Lisp
A lisp is a speech impairment in which a person misarticulates sibilants (, , , , , , , ). These misarticulations often result in unclear speech.
Types
* A frontal lisp occurs when the tongue is placed anterior to the target. Interdental lisping ...
syntax, which is different in both appearance and philosophy.
Adoption
Language rankings
, JVM-based languages such as Clojure, Groovy, Kotlin, Scala are highly ranked, but still significantly less popular than the original Java language, which is usually ranked in the top three places.
The Popularity of Programming Language Index, which tracks searches for language tutorials, ranked Scala 15th in April 2018 with a small downward trend, and 17th in Jan 2021. This makes Scala the 3rd most popular JVM-based language after Java and Kotlin, ranked 12th.
The TIOBE index
The TIOBE programming community index is a measure of popularity of programming languages, created and maintained by TIOBE Software BV, based in Eindhoven, the Netherlands. TIOBE stands for ''The Importance of Being Earnest'', the title of an 18 ...
of programming language popularity employs internet search engine rankings and similar publication-counting to determine language popularity. , it shows Scala in 31st place. In this ranking, Scala is ahead of Haskell
Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lang ...
(38th) and Erlang, but below Go (14th), Swift
Swift or SWIFT most commonly refers to:
* SWIFT, an international organization facilitating transactions between banks
** SWIFT code
* Swift (programming language)
* Swift (bird), a family of birds
It may also refer to:
Organizations
* SWIFT, ...
(15th), and Perl
Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
(19th).
The RedMonk Programming Language Rankings, which establishes rankings based on the number of GitHub
GitHub, Inc. () is an Internet hosting service for software development and version control using Git. It provides the distributed version control of Git plus access control, bug tracking, software feature requests, task management, continuous ...
projects and questions asked on Stack Overflow
In software, a stack overflow occurs if the call stack pointer exceeds the stack bound. The call stack may consist of a limited amount of address space, often determined at the start of the program. The size of the call stack depends on many fac ...
, ranks Scala 14th. Here, Scala is placed inside a second-tier group of languages–ahead of Go, PowerShell
PowerShell is a task automation and configuration management program from Microsoft, consisting of a command-line shell (computing), shell and the associated scripting language. Initially a Windows component only, known as Windows PowerShell, it ...
, and Haskell
Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lang ...
, and behind Swift
Swift or SWIFT most commonly refers to:
* SWIFT, an international organization facilitating transactions between banks
** SWIFT code
* Swift (programming language)
* Swift (bird), a family of birds
It may also refer to:
Organizations
* SWIFT, ...
, Objective-C
Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTS ...
, Typescript
TypeScript is a free and open source programming language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are ...
, and R.
In the 2018 edition of the ''State of Java'' survey, which collected data from 5160 developers on various Java-related topics, Scala places third in terms of use of alternative languages on the JVM. Relative to the prior year's edition of the survey, Scala's use among alternative JVM languages fell from 28.4% to 21.5%, overtaken by Kotlin, which rose from 11.4% in 2017 to 28.8% in 2018.
Back in 2013, when Scala was in version 2.10, the ThoughtWorks Technology Radar, which is an opinion based biannual report of a group of senior technologists, recommended Scala adoption in its languages and frameworks category. In July 2014, this assessment was made more specific and now refers to a “Scala, the good parts”, which is described as “To successfully use Scala, you need to research the language and have a very strong opinion on which parts are right for you, creating your own definition of Scala, the good parts.”.
Companies
* In April 2009, Twitter
Twitter is an online social media and social networking service owned and operated by American company Twitter, Inc., on which users post and interact with 280-character-long messages known as "tweets". Registered users can post, like, and ...
announced that it had switched large portions of its backend from Ruby
A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sa ...
to Scala and intended to convert the rest.
* Gilt uses Scala and Play Framework
Play Framework is an open-source software, open-source web application framework which follows the model–view–controller (MVC) architectural pattern (computer science), architectural pattern. It is written in Scala (programming language), Sc ...
.
* Foursquare
Four square is a ball game.
Four square may also refer to:
Internet and entertainment
* Foursquare City Guide, a local search and discovery app
* ''4 Square'' (game show), a British game show
* ''4 Square'' (TV series), a Canadian children's s ...
uses Scala and Lift
Lift or LIFT may refer to:
Physical devices
* Elevator, or lift, a device used for raising and lowering people or goods
** Paternoster lift, a type of lift using a continuous chain of cars which do not stop
** Patient lift, or Hoyer lift, mobile ...
.
* Coursera
Coursera Inc. () is a U.S.-based massive open online course provider founded in 2012 by Stanford University computer science professors Andrew Ng and Daphne Koller. Coursera works with universities and other organizations to offer online courses, ...
uses Scala and Play Framework
Play Framework is an open-source software, open-source web application framework which follows the model–view–controller (MVC) architectural pattern (computer science), architectural pattern. It is written in Scala (programming language), Sc ...
.
* Apple Inc.
Apple Inc. is an American multinational technology company headquartered in Cupertino, California, United States. Apple is the largest technology company by revenue (totaling in 2021) and, as of June 2022, is the world's biggest company b ...
uses Scala in certain teams, along with Java and the Play framework.
* ''The Guardian
''The Guardian'' is a British daily newspaper. It was founded in 1821 as ''The Manchester Guardian'', and changed its name in 1959. Along with its sister papers ''The Observer'' and ''The Guardian Weekly'', ''The Guardian'' is part of the Gu ...
'' newspaper's high-traffic website guardian.co.uk
TheGuardian.com, formerly known as Guardian.co.uk and ''Guardian Unlimited'', is a British news and media website owned by the Guardian Media Group. It contains nearly all of the content of the newspapers ''The Guardian'' and ''The Observer'', ...
announced in April 2011 that it was switching from Java to Scala.
* ''The New York Times
''The New York Times'' (''the Times'', ''NYT'', or the Gray Lady) is a daily newspaper based in New York City with a worldwide readership reported in 2020 to comprise a declining 840,000 paid print subscribers, and a growing 6 million paid ...
'' revealed in 2014 that its internal content management system ''Blackbeard'' is built using Scala, Akka, and Play.
* The ''Huffington Post
''HuffPost'' (formerly ''The Huffington Post'' until 2017 and sometimes abbreviated ''HuffPo'') is an American progressive news website, with localized and international editions. The site offers news, satire, blogs, and original content, and ...
'' newspaper started to employ Scala as part of its content delivery system ''Athena'' in 2013.
* Swiss bank UBS
UBS Group AG is a multinational Investment banking, investment bank and financial services company founded and based in Switzerland. Co-headquartered in the cities of Zürich and Basel, it maintains a presence in all major financial centres ...
approved Scala for general production use.
* LinkedIn
LinkedIn () is an American business and employment-oriented online service that operates via websites and mobile apps. Launched on May 5, 2003, the platform is primarily used for professional networking and career development, and allows job se ...
uses the Scalatra
Scalatra is a free and open source web application framework written in Scala. It is a port of the Sinatra framework written in Ruby. Scalatra is an alternative to the Lift, Play!, and Unfiltered frameworks.
Scalatra is an example of a microfr ...
microframework A microframework is a term used to refer to minimalistic web application frameworks. It is contrasted with full-stack frameworks.
It lacks most of the functionality which is common to expect in a full-fledged web application framework, such as:
* ...
to power its Signal API.
* Meetup
Meetup is a social media platform for hosting and organizing in-person and virtual activities, gatherings, and events for people and communities of similar interests, hobbies, and professions. It was founded in 2002 by Scott Heiferman and four ot ...
uses Unfiltered toolkit for real-time APIs.
* Remember the Milk
Remember the Milk (RTM) is an application service provider for Web-based task- and time-management. It allows users to manage tasks from a computer or smartphone, both online and offline. Created in 2004 by a two-person Australian company, it no ...
uses Unfiltered toolkit, Scala and Akka for public API and real-time updates.
* Verizon
Verizon Communications Inc., commonly known as Verizon, is an American multinational telecommunications conglomerate and a corporate component of the Dow Jones Industrial Average. The company is headquartered at 1095 Avenue of the Americas in ...
seeking to make "a next-generation framework" using Scala.
* Airbnb
Airbnb, Inc. ( ), based in San Francisco, California, operates an online marketplace focused on short-term homestays and experiences. The company acts as a broker and charges a commission from each booking. The company was founded in 2008 b ...
develops open-source machine-learning software "Aerosolve", written in Java and Scala.
* Zalando
Zalando SE is a publicly traded German online retailer of shoes, fashion and beauty. The company was founded in 2008 by David Schneider and Robert Gentz and has more than 50 million active users in 25 European markets. Zalando is active in a vari ...
moved its technology stack from Java to Scala and Play.
* SoundCloud
SoundCloud is an online audio distribution platform and music sharing website that enables its users to upload, promote, and share audio. Founded in 2007 by Alexander Ljung and Eric Wahlforss, SoundCloud is one of the largest music streaming se ...
uses Scala for its back-end, employing technologies such as Finagle (micro services), Scalding and Spark (data processing).
* Databricks
Databricks is an American enterprise software company founded by the creators of Apache Spark. Databricks develops a web-based platform for working with Spark, that provides automated cluster management and IPython-style notebooks.
History
Da ...
uses Scala for the Apache Spark
Apache Spark is an open-source unified analytics engine for large-scale data processing. Spark provides an interface for programming clusters with implicit data parallelism and fault tolerance. Originally developed at the University of Californi ...
Big Data platform.
* Morgan Stanley
Morgan Stanley is an American multinational investment management and financial services company headquartered at 1585 Broadway in Midtown Manhattan, New York City. With offices in more than 41 countries and more than 75,000 employees, the fir ...
uses Scala extensively in their finance and asset-related projects.
* There are teams within Google
Google LLC () is an American multinational technology company focusing on search engine technology, online advertising, cloud computing, computer software, quantum computing, e-commerce, artificial intelligence, and consumer electronics. ...
and Alphabet Inc.
Alphabet Inc. is an American multinational technology conglomerate holding company headquartered in Mountain View, California. It was created through a restructuring of Google on October 2, 2015, and became the parent company of Google and sev ...
that use Scala, mostly due to acquisitions such as Firebase
Firebase is a set of hosting services for any type of application (Android, iOS, Javascript, Node.js, Java, Unity, PHP, C++ ...). It offers NoSQL and real-time hosting of databases, content, social authentication (Google, Facebook, Twitter an ...
and Nest.
* Walmart Canada
Walmart Canada is the Canadian subsidiary of Walmart which is headquartered in Mississauga, Ontario. It was founded on March 17, 1994, with the purchase of the Woolco Canada chain from the F. W. Woolworth Company.
Originally consisting of disco ...
uses Scala for their back-end platform.
* Duolingo
Duolingo ( ) is an American educational technology company which produces learning apps and provides language certification.
On its main app, users can practice vocabulary, grammar, pronunciation and listening skills using spaced repetition. D ...
uses Scala for their back-end module that generates lessons.
* HMRC
, patch =
, patchcaption =
, logo = HM Revenue & Customs.svg
, logocaption =
, badge =
, badgecaption =
, flag =
, flagcaption =
, image_size =
, co ...
uses Scala for many UK Government tax applications.
*M1 Finance
M1 Finance (commonly abbreviated as M1) is an American financial services company. Founded in 2015, the company offers a robo-advisory investment platform with brokerage accounts, digital checking accounts, and lines of credit. M1 offers a ...
uses Scala for their back-end platform.
Criticism
In March 2015, former VP of the Platform Engineering group at Twitter Raffi Krikorian
Raffi Krikorian ( hy, Րաֆֆի Գրիգորեան; born 1978) is an Armenian-American technology executive, and the CTO of the Emerson Collective. He was the CTO of the Democratic National Committee, Head of Uber's Advanced Technologies Center, ...
, stated that he would not have chosen Scala in 2011 due to its learning curve
A learning curve is a graphical representation of the relationship between how Skill, proficient people are at a task and the amount of experience they have. Proficiency (measured on the vertical axis) usually increases with increased experience ...
. The same month, LinkedIn SVP Kevin Scott stated their decision to "minimize heir
Inheritance is the practice of receiving private property, titles, debts, entitlements, privileges, rights, and obligations upon the death of an individual. The rules of inheritance differ among societies and have changed over time. Officiall ...
dependence on Scala". In November 2011, Yammer
Yammer () is an enterprise social networking service that is part of the Microsoft 365 family of products. It is used mainly for private communication within organizations but is also used for networks spanning various organizations. Access to a ...
moved away from Scala for reasons that included the learning curve for new team members and incompatibility from one version of the Scala compiler to the next.
See also
* sbt
sbt is an open-source build tool for Scala and Java projects, similar to Apache's Maven and Gradle.
Its main features are:
*Native support for compiling Scala code and integrating with many Scala test frameworks
*Continuous compilation, t ...
, a widely used build tool for Scala projects
* Play!
Play! is a pavilion, which was scheduled to open at Epcot by the spring of 2023. It will be built in the former Wonders of Life pavilion and will be themed like an interactive city in which guests will be able to interact with their favorite Disn ...
, an open-source Web application framework that supports Scala
* Akka
Akka or AKKA may refer to:
Arts and entertainment
* ''Akka'' (film), a 1976 Indian Tamil film
* ''Akka'' (TV series), a 2014–2015 Indian Tamil soap opera
* Akka, a character in the children's novel ''The Wonderful Adventures of Nils'' by Selma ...
, an open-source toolkit for building concurrent and distributed applications
* Chisel
A chisel is a tool with a characteristically shaped cutting edge (such that wood chisels have lent part of their name to a particular grind) of blade on its end, for carving or cutting a hard material such as wood, stone, or metal by hand, stru ...
, an open-source language built on Scala that is used for hardware design and generation.
References
Further reading
*
*
*
*
*
*
{{Authority control
Programming languages
Articles with example Scala code
Concurrent programming languages
Free software programmed in Scala
Functional languages
Java programming language family
JVM programming languages
Object-oriented programming languages
Pattern matching programming languages
Programming languages created in 2003
Scripting languages
Software using the Apache license
Statically typed programming languages
2003 software
Cross-platform free software
Free compilers and interpreters
Source-to-source compilers