Scala source code can be compiled toJava bytecode and run on aJava virtual machine (JVM). Scala can also betranspiled toJavaScript to run in a browser, or compiled directly to a native executable. When running on the JVM, Scala provideslanguage interoperability withJava so that libraries written in either language may be referenced directly in Scala or Java code.[10] Like Java, Scala isobject-oriented, and uses asyntax termedcurly-brace which is similar to the languageC. Since Scala 3, there is also an option to use theoff-side rule (indenting) to structureblocks, and its use is advised.Martin Odersky has said that this turned out to be the most productive change introduced in Scala 3.[11]
After an internal release in late 2003, Scala was released publicly in early 2004 on theJava platform,[15][6][14][16] A second version (v2.0) followed in March 2006.[6]
On 17 January 2011, the Scala team won a five-year research grant of over €2.3 million from theEuropean Research Council.[17] On 12 May 2011, Odersky and collaborators launched Typesafe Inc. (later renamedLightbend Inc.), a company to provide commercial support, training, and services for Scala. Typesafe received a $3 million investment in 2011 fromGreylock Partners.[18][19][20][21]
Scala runs on theJava platform (Java virtual machine) and is compatible with existingJava programs.[15] AsAndroid applications are typically written in Java and translated from Java bytecode intoDalvik bytecode (which may be further translated to native machine code during installation) when packaged, Scala's Java compatibility makes it well-suited to Android development, the more so when a functional approach is preferred.[22]
The reference Scala software distribution, including compiler and libraries, is released under theApache license.[23]
Scala.js is a Scala compiler that compiles to JavaScript, making it possible to write Scala programs that can run in web browsers orNode.js.[24] The compiler, in development since 2013, was announced as no longer experimental in 2015 (v0.6). Version v1.0.0-M1 was released in June 2018 and version 1.1.1 in September 2020.[25]
Scala Native is a Scalacompiler that targets theLLVM compiler infrastructure to create executable code that uses a lightweight managed runtime, which uses theBoehm garbage collector. The project is led by Denys Shabalin and had its first release, 0.1, on 14 March 2017. Development of Scala Native began in 2015 with a goal of being faster thanjust-in-time compilation for the JVM by eliminating the initial runtime compilation of code and also providing the ability to call native routines directly.[26][27]
When the program is stored in fileHelloWorld.scala, the user compiles it with the command:
$ scalac HelloWorld.scala
and runs it with
$ scala HelloWorld
This is analogous to the process for compiling and running Java code. Indeed, Scala's compiling and executing model is identical to that of Java, making it compatible with Java build tools such asApache Ant.
A shorter version of the "Hello World" Scala program is:
println("Hello, World!")
Scala includes an interactive shell and scripting support.[29] Saved in a file namedHelloWorld2.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-e:
$ scala-e 'println("Hello, World!")'
Expressions can be entered interactively in theREPL:
$scalaWelcome to Scala 2.12.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_131).Type in expressions for evaluation. Or try :help.scala> List(1, 2, 3).map(x => x * x)res0: List[Int] = List(1, 4, 9)scala>
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.,):
// Scala: Direct conversion from Java// no import needed; scala.math// already imported as `math`defmathFunction(num:Int):Int=varnumSquare:Int=num*numreturn(math.cbrt(numSquare)+math.log(numSquare)).asInstanceOf[Int]
// Scala: More idiomatic// Uses type inference, omits `return` statement,// uses `toInt` method, declares numSquare immutableimportmath.*defmathFunction(num:Int)=valnumSquare=num*num(cbrt(numSquare)+log(numSquare)).toInt
Some syntactic differences in this code are:
Scala does not require semicolons (;) to end statements.
Value types are capitalized (sentence case):Int, Double, Boolean instead ofint, double, boolean.
Parameter and return types follow, as inPascal, rather than precede as inC.
Methods must be preceded bydef.
Local or class variables must be preceded byval (indicates animmutable variable) orvar (indicates amutable variable).
Thereturn 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 usesfoo.asInstanceOf[Type], or a specialized function such astoDouble ortoInt.
Function or methodfoo() can also be called as justfoo; methodthread.send(signo) can also be called as justthread send signo; and methodfoo.toString() can also be called as justfoo toString.
Array references are written like function calls, e.g.array(i) rather thanarray[i]. (Internally in Scala, the former expands into array.apply(i) which returns the reference)
Generic types are written as e.g.List[String] rather than Java'sList<String>.
Instead of the pseudo-typevoid, Scala has the actualsingleton classUnit (see below).
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 hassingleton objects, which are essentially classes with only one instance. Singleton objects are declared usingobject instead ofclass. 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 acompanion object.[15] (The underlying class for the singleton object has a$ appended. Hence, forclass Foo with companion objectobject Foo, under the hood there's a classFoo$ containing the companion object's code, and one object of this class is created, using thesingleton pattern.)
In place of constructor parameters, Scala hasclass parameters, which are placed on the class, similar to parameters to a function. When declared with aval orvar 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 thedefault constructor (other than initializing the member variables) goes directly at class level.
In Scala it is possible to define operators by using symbols as method names. In place ofaddPoint, the Scala example defines+=, which is then invoked withinfix notation asgrid += this.
Scala has the same compiling model asJava andC#, namely separate compiling anddynamic 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.[15] In fact, Scala code can bedecompiled to readable Java code, with the exception of certain constructor operations. To theJava virtual machine (JVM), Scala code and Java code are indistinguishable. The only difference is one extra runtime library,scala-library.jar.[30]
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 severalcorner cases in Java. From the Scala perspective, this is practically important because several added features in Scala are also available in C#.
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 aninfix 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.
Methodsapply andupdate have syntactic short forms.foo()—wherefoo is a value (singleton object or class instance)—is short forfoo.apply(), andfoo() = 42 is short forfoo.update(42). Similarly,foo(42) is short forfoo.apply(42), andfoo(4) = 2 is short forfoo.update(4, 2). This is used for collection classes and extends to many other cases, such asSTM 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., usingfoo.toString instead offoo.toString(). By convention, a method should be defined with empty-parens when it performsside effects.
Method names ending in colon (:) expect the argument on the left-hand-side and the receiver on the right-hand-side. For example, the4 :: 2 :: Nil is the same asNil.::(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. Fortrait FooLike { var bar: Int }, an implementation may beobjectFooextendsFooLike{privatevarx=0;defbar=x;defbar_=(value:Int){x=value}}}}. The call site will still be able to use a concisefoo.bar = 42.
The use of curly braces instead of parentheses is allowed in method calls. This allows pure library implementations of new control structures.[31] For example,breakable { ... if (...) break() ... } looks as ifbreakable was a language defined keyword, but really is just a method taking athunk 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) { math.random } is the same asVector.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 asmap,flatMap andfilter.
By themselves, these may seem like questionable choices, but collectively they serve the purpose of allowingdomain-specific languages 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.
Java makes a sharp distinction between primitive types (e.g.int andboolean) and reference types (anyclass). Only reference types are part of the inheritance scheme, deriving fromjava.lang.Object. In Scala, all types inherit from a top-level classAny, whose immediate children areAnyVal (value types, such asInt andBoolean) andAnyRef (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 and unboxing is completely transparent to the user. Scala 2.10 allows for new value types to be defined by the user.
Instead of the Java "foreach" loops for looping through an iterator, Scala hasfor-expressions, which are similar tolist comprehensions in languages such asHaskell, or a combination of list comprehensions andgenerator expressions inPython. For-expressions using theyield keyword allow a newcollection 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 ofmap,flatMap andfilter calls. Whereyield is not used, the code approximates to an imperative-style loop, by translating toforeach.
(Note that the expression1 to 25 is not special syntax. The methodto is rather defined in the standard Scala library as an extension method on integers, using a technique known as implicit conversions[32] 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).valdem_mentions=for(mention,times)<-mentionsaccount<-accounts.get(mention)ifaccount.party=="Democratic"yield(account,times)
Expression(mention, times) <- mentions is an example ofpattern matching (see below). Iterating over a map returns a set of key-valuetuples, 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 variablementions) is a map. Note that ifmentions 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.
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 infunctional programming 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.
UnlikeC orJava, but similar to languages such asLisp, Scala makes no distinction between statements andexpressions. All statements are in fact expressions that evaluate to some value. Functions that would be declared as returningvoid in C or Java, and statements likewhile that logically do not return a value, are in Scala considered to return the typeUnit, which is asingleton type, with only one object of that type. Functions and operators that never return at all (e.g. thethrow operator or a function that always exitsnon-locally using an exception) logically have return typeNothing, a special type containing no objects; that is, abottom type, i.e. a subclass of every possible type. (This in turn makes typeNothing compatible with every type, allowingtype inference to function correctly.)[33]
Similarly, anif-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 aternary operator in Scala:
For similar reasons,return statements are unnecessary in Scala, and in fact are discouraged. As inLisp, 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 returnUnit are written with an equals sign
defprintValue(x:String):Unit=println("I ate a %s".format(x))
or equivalently (with type inference, and omitting the unnecessary newline):
defprintValue(x:String)=println("I ate a %s"formatx)
Due totype inference, the type of variables, function return values, and many other expressions can typically be omitted, as the compiler can deduce it. Examples areval x = "foo" (for an immutableconstant orimmutable object) orvar x = 1.5 (for a variable whose value can later be changed). Type inference in Scala is essentially local, in contrast to the more globalHindley-Milner algorithm used in Haskell,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 ofrecursive functions), e.g.
defformatApples(x:Int)="I ate %d apples".format(x)
or (with a return type declared for a recursive function)
In Scala, functions are objects, and a convenient syntax exists for specifyinganonymous functions. An example is the expressionx => 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)(<x2)). Note that neither the type ofx nor the return type need be explicitly specified, and can generally be inferred bytype inference; but they can be explicitly specified, e.g. as(x:Int)=>x<2 or even(x:Int)=>(x<2):Boolean.
Anonymous functions behave as trueclosures 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'sanonymous 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 usesplaceholder variables: For example, the following:
Scala enforces a distinction between immutable and mutable variables. Mutable variables are declared using thevar keyword and immutable values are declared using theval keyword.A variable declared using theval keyword cannot be reassigned in the same way that a variable declared using thefinal keyword can't be reassigned in Java.vals 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 immutablecollection 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.[34]The immutable variants arepersistent data structures that always return an updated copy of an old object instead of updating the old object destructively in place.An example of this isimmutable 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.[35]
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 thelazy 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 typeStream, a non-strict linked list), and any collection can be made non-strict with theview 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.
Functional programming languages commonly providetail call optimization to allow for extensive use ofrecursion withoutstack overflow 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.Trampolines have been suggested as a workaround.[36] Trampoline support has been provided by the Scala library with the objectscala.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.[37]
An example of this optimization could be implemented using thefactorial definition. For instance, the recursive version of the factorial:
However, this could compromise composability with other functions because of the new argument on its definition, so it is common to useclosures to preserve its original signature:
deffactorial(n:Int):Int=@tailrecdefloop(current:Int,accum:Int):Int=ifcurrent==0thenaccumelseloop(current-1,current*accum)loop(n,1)// Call to the closure using the base caseendfactorial
This ensures tail call optimization and thus prevents a stack overflow error.
Scala has built-in support forpattern matching, which can be thought of as a more sophisticated, extensible version of aswitch statement, 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 acase class is provided, which includes automatic support for pattern matching and can be used to model thealgebraic data types 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 thequicksort algorithm using pattern matching is this:
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 samedivide-and-conquer strategy ofmergesort and other fast sorting algorithms.
Thematch operator is used to do pattern matching on the object stored inlist. Eachcase 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 objectNil, butpivot :: tail matches a non-empty list, and simultaneouslydestructures the list according to the pattern given. In this case, the associated code will have access to a local variable namedpivot holding the head of the list, and another variabletail holding the tail of the list. Note that these variables are read-only, and are semantically very similar to variablebindings established using thelet operator in Lisp and Scheme.
Pattern matching also happens in local variable declarations. In this case, the return value of the call totail.partition is atuple — 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 ananonymous function 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 tocons in Lisp and Scheme) and::: (which appends two lists together, similar toappend 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"-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.)
In the pattern-matching example above, the body of thematch operator is apartial function, which consists of a series ofcase expressions, with the first matching expression prevailing, similar to the body of aswitch statement. Partial functions are also used in the exception-handling portion of atry statement:
Finally, a partial function can be used alone, and the result of calling it is equivalent to doing amatch over it. For example, the prior code forquicksort can be written thus:
Here a read-onlyvariable 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:
Traits are Scala's replacement for Java'sinterfaces. 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 tomixin 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. Thesuper operator behaves specially in traits, allowing traits to be chained using composition in addition to inheritance. The following example is a simple window system:
abstractclassWindow:// abstractdefdraw()classSimpleWindowextendsWindow:defdraw()println("in SimpleWindow")// draw a basic windowtraitWindowDecorationextendsWindowtraitHorizontalScrollbarDecorationextendsWindowDecoration:// "abstract override" is needed here for "super()" to work because the parent// function is abstract. If it were concrete, regular "override" would be enough.abstractoverridedefdraw()println("in HorizontalScrollbarDecoration")super.draw()// now draw a horizontal scrollbartraitVerticalScrollbarDecorationextendsWindowDecoration:abstractoverridedefdraw()println("in VerticalScrollbarDecoration")super.draw()// now draw a vertical scrollbartraitTitleDecorationextendsWindowDecoration:abstractoverridedefdraw()println("in TitleDecoration")super.draw()// now draw the title bar
In other words, the call todraw first executed the code inTitleDecoration (the last trait mixed in), then (through thesuper() calls) threaded back through the other mixed-in traits and eventually to the code inWindow,even though none of the traits inherited from one another. This is similar to thedecorator pattern, 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 ofimplementation inheritance, 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.
Scala is equipped with an expressive static type system that mostly enforces the safe and coherent use of abstractions. The type system is, however, notsound.[38] In particular, the type system supports:
Scala is able toinfer 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.
A common technique in Scala, known as "enrich my library"[39] (originally termed "pimp my library" by Martin Odersky in 2006;[32] concerns were raised about this phrasing due to its negative connotations[40] and immaturity[41]), allows new methods to be used as if they were added to existing types. This is similar to the C# concept ofextension methods 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 animplicit conversion 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 thatimports the add-on library gets the new functionality, and all other code is unaffected.
The following example shows the enrichment of typeInt with methodsisEven andisOdd:
objectMyExtensions:extension(i:Int)defisEven=i%2==0defisOdd=!i.isEvenimportMyExtensions.*// bring implicit enrichment into scope4.isEven// -> true
Importing the members ofMyExtensions brings the implicit conversion to extension classIntPredicates into scope.[42]
An Actor is like a thread instance with a mailbox. It can be created bysystem.actorOf, overriding thereceive method to receive messages and using the! (exclamation point) method to send a message.[45]The following example shows an EchoServer that can receive messages and then print them.
Scala also comes with built-in support for data-parallel programming in the form of Parallel Collections[46] integrated into its Standard Library since version 2.9.0.
The following example shows how to use Parallel Collections to improve performance.[47]
valurls=List("https://scala-lang.org","https://github.com/scala/scala")deffromURL(url:String)=scala.io.Source.fromURL(url).getLines().mkString("\n")valt=System.currentTimeMillis()urls.par.map(fromURL(_))// par returns parallel implementation of a collectionprintln("time: "+(System.currentTimeMillis-t)+"ms")
Besides futures and promises, actor support, anddata parallelism, Scala also supports asynchronous programming with software transactional memory, and event streams.[48]
The most well-known open-source cluster-computing solution written in Scala isApache Spark. Additionally,Apache Kafka, thepublish–subscribemessage queue popular with Spark and other stream processing technologies, is written in Scala.
There are several ways to test code in Scala. ScalaTest supports multiple testing styles and can integrate with Java-based testing frameworks.[49] ScalaCheck is a library similar to Haskell'sQuickCheck.[50] specs2 is a library for writing executable software specifications.[51] ScalaMock provides support for testing high-order and curried functions.[52]JUnit andTestNG are popular testing frameworks written in Java.
Scala is often compared withGroovy andClojure, 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 isstatically typed, while both Groovy and Clojure aredynamically typed. This makes the type system more complex and difficult to understand but allows almost all[38] 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 aninvoke 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, 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 theLisp syntax, which is different in both appearance and philosophy.[citation needed]
Back in 2013, when Scala was in version 2.10, theThoughtWorks Technology Radar, which is an opinion based biannual report of a group of senior technologists,[139] recommended Scala adoption in its languages and frameworks category.[140]
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.”.[141]
In the 2018 edition of theState ofJava survey,[142] which collected data from 5160 developers on various Java-related topics, Scala places third in terms of use of alternative languages on theJVM. Relative to the prior year's edition of the survey, Scala's use among alternativeJVM languages fell from 28.4% to 21.5%, overtaken byKotlin, which rose from 11.4% in 2017 to 28.8% in 2018.The Popularity of Programming Language Index,[143] 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 afterJava and Kotlin, ranked 12th.
TheTIOBE index[145] of programming language popularity employs internet search engine rankings and similar publication counting to determine language popularity. In September 2021, it showed Scala in 31st place. In this ranking, Scala was ahead of Haskell (38th) andErlang, but belowGo (14th),Swift (15th), andPerl (19th).
As of 2022[update], JVM-based languages such as Clojure, Groovy, and Scala are highly ranked, but still significantly less popular than the originalJava language, which is usually ranked in the top three places.[144][145]
In April 2009,Twitter announced that it had switched large portions of its backend fromRuby to Scala and intended to convert the rest.[146]
Tesla, Inc. usesAkka with Scala in the backend of the Tesla Virtual Power Plant. Thereby, theActor model is used for representing and operating devices that together with other components make up an instance of the virtual power plant, andReactive Streams are used for data collection and data processing.[147]
Apache Kafka is implemented in Scala with regards to most of its core and other critical parts. It is maintained and extended through the open source project and by the company Confluent.[148]
In November 2011,Yammer 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.[175] In March 2015, former VP of the Platform Engineering group atTwitterRaffi Krikorian, stated that he would not have chosen Scala in 2011 due to itslearning curve.[176] The same month,LinkedIn SVPKevin Scott stated their decision to "minimize [their] dependence on Scala".[177]
^Martin Odersky (17 June 2020).Martin Odersky: A Scala 3 Update (video). YouTube. Event occurs at 36:35–45:08.Archived from the original on 2021-12-21. Retrieved2021-04-24.
^"Home". Blog.lostlake.org. Archived fromthe original on 31 August 2010. Retrieved2013-06-25.
^Scala's built-in control structures such asif orwhile cannot be re-implemented. There is a research project, Scala-Virtualized, that aimed at removing these restrictions: Adriaan Moors, Tiark Rompf, Philipp Haller and Martin Odersky.Scala-Virtualized.Proceedings of the ACM SIGPLAN 2012 workshop on Partial evaluation and program manipulation, 117–120. July 2012.
^Giarrusso, Paolo G. (2013). "Reify your collection queries for modularity and speed!".Proceedings of the 12th annual international conference on Aspect-oriented software development. ACM.arXiv:1210.6284.Bibcode:2012arXiv1210.6284G.Also known as pimp-my-library pattern
^Implicit classes were introduced in Scala 2.10 to make method extensions more concise. This is equivalent to adding a methodimplicit def IntPredicate(i: Int) = new IntPredicate(i). The class can also be defined asimplicit class IntPredicates(val i: Int) extends AnyVal { ... }, producing a so-calledvalue class, also introduced in Scala 2.10. The compiler will then eliminate actual instantiations and generate static methods instead, allowing extension methods to have virtually no performance overhead.