Scala (programming language): Difference between revisions

Content deleted Content added
m Spelling
m ln source to source compiling
 
(23 intermediate revisions by 20 users not shown)
Line 1:
{{Short description|General-purpose programming language}}
{{For|the music scale creation software|Scala (software)}}
 
{{Infobox programming language
| name = Scala
| logo = Scala-full-color.svg
| logo_size = 180px
| paradigm = [[Multi-paradigm programming language|Multi-paradigm]]: [[Concurrent programming|concurrent]], [[Functional programming|functional]], [[Imperative programming|imperative]], [[Object-oriented programming|object-oriented]]
| designer = [[Martin Odersky]]
| developer = Programming Methods Laboratory of [[École Polytechnique Fédérale de Lausanne]]
Line 17 ⟶ 19:
| latest release date = {{start date and age|{{wikidata|qualifier|single|P548=Q2804309|P348|P577}}}}
| file ext = .scala, .sc
| influenced by = [[Common Lisp]],<ref name="Scala Macros">{{cite web |title=Scala Macros |url=http://scalamacros.org}}</ref> [[Eiffel (programming language)|Eiffel]], [[Erlang (programming language)|Erlang]], [[F Sharp (programming language)|F#]], [[Haskell (programming language)|Haskell]],<ref>{{cite web |url=http://blog.fogus.me/2010/08/06/martinodersky-take5-tolist/ |title=MartinOdersky take(5) toList|last=Fogus|first=Michael |date=6 August 2010|work=Send More Paramedics |access-date=2012-02-09}}</ref> [[Java (programming language)|Java]],<ref name="popl06">{{cite web |url=https://lampwww.epfl.ch/~odersky/talks/popl06.pdf |title=The Scala Experiment - Can We Provide Better Language Support for Component Systems? |last=Odersky|first=Martin |date=11 January 2006 |access-date=2016-06-22}}</ref> [[OCaml]],<ref name="popl06"/> [[Oz (programming language)|Oz]], [[Pizza (programming language)|Pizza]],<ref name="overview">{{cite web |last1=Odersky |first1=Martin |display-authors=etal |title=An Overview of the Scala Programming Language |edition=2nd |url=https://www.scala-lang.org/docu/files/ScalaOverview.pdf |publisher=École Polytechnique Fédérale de Lausanne (EPFL) |url-status=live |archive-url=https://web.archive.org/web/20200709211816/https://www.scala-lang.org/docu/files/ScalaOverview.pdf |archive-date=2020-07-09 |date=2006}}</ref> [[Scheme (programming language)|Scheme]],<ref name="popl06"/> [[Smalltalk]], [[Standard ML]]<ref name="popl06"/>
| influenced = [[Ceylon (programming language)|Ceylon]], [[Chisel (programming language)|Chisel]], [[Fantom (programming language)|Fantom]], [[F Sharp (programming language)|F#]], [[C Sharp (programming language)|C#]], [[Kotlin (programming language)|Kotlin]], [[Lasso (programming language)|Lasso]], [[Red (programming language)|Red]], [[Flix (programming language)|Flix]]
}}
'''Scala''' ({{IPAc-en|ˈ|s|k|ɑː|l|ɑː}} {{respell|SKAH|lah}})<ref>{{cite book |last=Odersky |first=Martin |date=2008 |title=Programming in Scala |url=https://books.google.com/books?id=MFjNhTjeQKkC&q=scala%20is%20pronounced%20skah-lah&pg=PA3 |___location=Mountain View, California |publisher=Artima |page=3 |isbn=9780981531601 |access-date=12 June 2014}}</ref><ref>{{cite book |last1=Wampler |first1=Dean |last2=Payne |first2=Alex |title=Programming Scala: Scalability = Functional Programming + Objects |date=15 September 2009 |publisher=O'Reilly Media, Inc. |isbn=978-1-4493-7926-1 |page=7 |url=https://books.google.com/books?id=mincYfsQleMC&dq=scala+pronunciation&pg=PA7 |access-date=13 May 2024 |language=en |quote=The creators of Scala actually pronounce it ''scah-lah'', like the Italian word for "stairs." The two "a"s are pronounced the same.}}</ref> is a [[Strong and weak typing|strong]] [[Static typing|statically typed]] [[High-level programming language|high-level]] [[general-purpose programming language]] that supports both [[object-oriented programming]] and [[functional programming]]. Designed to be concise,<ref>{{Cite book |arxiv=1509.07326|volume=7916 |last1=Potvin |first1=Pascal |last2=Bonja |first2=Mario |title=SDL 2013: Model-Driven Dependability Engineering |date=24 September 2015 |doi= 10.1007/978-3-642-38911-5|series=Lecture Notes in Computer Science |isbn=978-3-642-38910-8 |s2cid=1214469}}</ref> many of Scala's design decisions are intended to address [[criticism of Java|criticisms of Java]].<ref name="overview"/>
 
'''Scala''' ({{IPAc-en|ˈ|s|k|ɑː|l|ɑː}} {{respell|SKAH|lah}})<ref>{{cite book |last=Odersky |first=Martin |date=2008 |title=Programming in Scala |url=https://books.google.com/books?id=MFjNhTjeQKkC&q=scala%20is%20pronounced%20skah-lah&pg=PA3 |___location=Mountain View, California |publisher=Artima |page=3 |isbn=9780981531601 |access-date=12 June 2014}}</ref><ref>{{cite book |last1=Wampler |first1=Dean |last2=Payne |first2=Alex |title=Programming Scala: Scalability = Functional Programming + Objects |date=15 September 2009 |publisher=O'Reilly Media, Inc. |isbn=978-1-4493-7926-1 |page=7 |url=https://books.google.com/books?id=mincYfsQleMC&dq=scala+pronunciation&pg=PA7 |access-date=13 May 2024 |language=en |quote=The creators of Scala actually pronounce it ''scah-lah'', like the Italian word for "stairs." The two "a"s are pronounced the same.}}</ref> is a [[Strong and weak typing|strongstrongly]] [[Static typing|statically typed]] [[High-level programming language|high-level]] [[general-purpose programming language]] that supports both [[object-oriented programming]] and [[functional programming]]. Designed to be concise,<ref>{{Cite book |arxiv=1509.07326|volume=7916 |last1=Potvin |first1=Pascal |last2=Bonja |first2=Mario |title=SDL 2013: Model-Driven Dependability Engineering |date=24 September 2015 |doi= 10.1007/978-3-642-38911-5|series=Lecture Notes in Computer Science |isbn=978-3-642-38910-8 |s2cid=1214469}}</ref> many of Scala's design decisions are intended to address [[criticism of Java|criticisms of Java]].<ref name="overview"/>
Scala source code can be compiled to [[Java bytecode]] and run on a [[Java virtual machine]] (JVM). Scala can also be transpiled to [[JavaScript]] to run in a browser, or compiled directly to a native executable. When running on the JVM, Scala provides [[language interoperability]] with [[Java (programming language)|Java]] so that libraries written in either language may be referenced directly in Scala or Java code.<ref>{{cite web |url=https://www.scala-lang.org/old/faq/4 |title=Frequently Asked Questions: Java Interoperability |author=<!--Staff writer(s); no by-line.--> |website=Scala-lang.org |access-date=2015-02-06}}</ref> Like Java, Scala is [[Object-oriented programming|object-oriented]], and uses a [[Syntax (programming languages)|syntax]] termed ''[[List of programming languages by type#Curly-bracket languages|curly-brace]]'' which is similar to the language [[C (programming language)|C]]. Since Scala 3, there is also an option to use the [[off-side rule]] (indenting) to structure [[Block (programming)|blocks]], and its use is advised. [[Martin Odersky]] has said that this turned out to be the most productive change introduced in Scala 3.<ref>{{Cite AV media |people=Martin Odersky |date=17 June 2020 |title=Martin Odersky: A Scala 3 Update |medium=video |language=en |url=https://www.youtube.com/watch?v=Z0w_pITUTyU |archive-url=https://ghostarchive.org/varchive/youtube/20211221/Z0w_pITUTyU |archive-date=2021-12-21 |url-status=live|time=36:35–45:08 |publisher=YouTube |access-date=2021-04-24}}{{cbignore}}</ref>
 
Scala source code can be compiled to [[Java bytecode]] and run on a [[Java virtual machine]] (JVM). Scala can also be [[transpiled]] to [[JavaScript]] to run in a browser, or compiled directly to a native executable. When running on the JVM, Scala provides [[language interoperability]] with [[Java (programming language)|Java]] so that libraries written in either language may be referenced directly in Scala or Java code.<ref>{{cite web |url=https://www.scala-lang.org/old/faq/4 |title=Frequently Asked Questions: Java Interoperability |author=<!--Staff writer(s); no by-line.--> |website=Scala-lang.org |access-date=2015-02-06}}</ref> Like Java, Scala is [[Object-oriented programming|object-oriented]], and uses a [[Syntax (programming languages)|syntax]] termed ''[[List of programming languages by type#Curly- bracket languages|curly-brace]]'' which is similar to the language [[C (programming language)|C]]. Since Scala 3, there is also an option to use the [[off-side rule]] (indenting) to structure [[Block (programming)|blocks]], and its use is advised. [[Martin Odersky]] has said that this turned out to be the most productive change introduced in Scala 3.<ref>{{Cite AV media |people=Martin Odersky |date=17 June 2020 |title=Martin Odersky: A Scala 3 Update |medium=video |language=en |url=https://www.youtube.com/watch?v=Z0w_pITUTyU |archive-url=https://ghostarchive.org/varchive/youtube/20211221/Z0w_pITUTyU |archive-date=2021-12-21 |url-status=live|time=36:35–45:08 |publisher=YouTube |access-date=2021-04-24}}{{cbignore}}</ref>
 
Unlike Java, Scala has many features of [[functional programming]] languages (like [[Scheme (programming language)|Scheme]], [[Standard ML]], and [[Haskell (programming language)|Haskell]]), including [[currying]], [[immutability]], [[lazy evaluation]], and [[pattern matching]]. It also has an advanced type system supporting [[algebraic data type]]s, [[covariance and contravariance (computer science)|covariance and contravariance]], [[higher-order type operator|higher-order types]] (but not [[Parametric polymorphism|higher-rank types]]), [[anonymous type]]s, [[operator overloading]], [[Option type|optional parameters]], [[named parameter]]s, [[raw string]]s, and an experimental exception-only version of algebraic effects that can be seen as a more powerful version of Java's [[checked exception]]s.<ref>{{Cite web|title=Effect expt|url=https://docs.scala-lang.org/scala3/reference/experimental/canthrow.html|access-date=2022-07-31|website=scala}}</ref>
 
The name Scala is a portmanteau of ''scalable'' and ''language'', signifying that it is designed to grow with the demands of its users.<ref name="StepsInScala">{{cite book |last=Loverdo |first=Christos |date=2010 |title=Steps in Scala: An Introduction to Object-Functional Programming |url=https://books.google.com/books?id=vZAfN_Vk2i0C&q=%22steps+in+scala%22&pg=PR13 |publisher=[[Cambridge University Press]] |page=xiii |isbn=9781139490948 |access-date=31 July 2014}}</ref>
Line 31 ⟶ 34:
The design of Scala started in 2001 at the [[École Polytechnique Fédérale de Lausanne]] (EPFL) (in [[Lausanne]], [[Switzerland]]) by [[Martin Odersky]]. It followed on from work on Funnel, a programming language combining ideas from functional programming and [[Petri net]]s.<ref name="history-of-scala">{{Cite web |last=Odersky |first=Martin |date=9 June 2006 |url=https://www.artima.com/weblogs/viewpost.jsp?thread=163733 |title=A Brief History of Scala |website=Artima.com}}</ref> Odersky formerly worked on [[Generic Java]], and [[javac]], Sun's Java compiler.<ref name="history-of-scala"/>
 
After an internal release in late 2003, Scala was released publicly in early 2004 on the [[Java (software platform)|Java platform]],<ref name="cacm">{{Cite journal |last1=Odersky |first1=M. |last2=Rompf |first2=T. |year=2014 |title=Unifying functional and object-oriented programming with Scala |journal=Communications of the ACM |volume=57 |issue=4 |page=76 |doi=10.1145/2591013 |doi-access=free}}</ref><!-- Overview says January 2004, spec says November 2003. --><ref name="overview"/><ref name="history-of-scala"/><ref name="spec">Martin Odersky, "The Scala Language Specification Version 2.7"</ref> A second version (v2.0) followed in March 2006.<ref name="overview"/>
 
On 17 January 2011, the Scala team won a five-year research grant of over €2.3 million from the [[European Research Council]].<ref>{{cite web|url=https://www.scala-lang.org/node/8579|title=Scala Team Wins ERC Grant|access-date=4 July 2015}}</ref> On 12 May 2011, Odersky and collaborators launched Typesafe Inc. (later renamed [[Lightbend Inc.]]), a company to provide commercial support, training, and services for Scala. Typesafe received a $3 million investment in 2011 from [[Greylock Partners]].<ref>{{cite web |url=https://www.scala-lang.org/node/9484 |title=Commercial Support for Scala |date=2011-05-12 |access-date=2011-08-18}}</ref><ref>{{cite web |url=https://medium.com/@greylockvc/why-we-invested-in-typesafe-modern-applications-demand-modern-tools-b6f7deec8b89 |title=Why We Invested in Typesafe: Modern Applications Demand Modern Tools |date=2011-05-12 |access-date=2018-05-08}}</ref><ref>{{cite web |url=https://news.cnet.com/8301-13846_3-20062090-62.html |title=Open-source Scala gains commercial backing |date=2011-05-12 |access-date=2011-10-09}}</ref><ref>{{cite web |url=https://www.mercurynews.com/business/ci_18048434 |title=Cloud computing pioneer Martin Odersky takes wraps off his new company Typesafe |date=2011-05-12 |access-date=2011-08-24}}</ref>
 
== Platforms and license ==
Scala runs on the [[Java (software platform)|Java platform]] ([[Java virtual machine]]) and is compatible with existing [[Java (programming language)|Java]] programs.<ref name="cacm"/> As [[Android (operating system)|Android]] applications are typically written in Java and translated from Java bytecode into [[Dalvik (software)|Dalvik]] 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.<ref>{{cite web|url=https://scala-android.org/|title=Scala on Android|access-date=8 June 2016|archive-date=20 June 2016|archive-url=https://web.archive.org/web/20160620223823/http://scala-android.org/|url-status=dead}}</ref>
 
The reference Scala software distribution, including compiler and libraries, is released under the [[Apache license]].<ref name="Scala 2.12.8 is now available!">{{cite web |url=https://www.scala-lang.org/news/2.12.8 |title= Scala 2.12.8 is now available! |date=2018-12-04 |access-date=2018-12-09}}</ref>
 
=== Other compilers and targets ===
[https://www.scala-js.org/ ''Scala.js''] is a Scala compiler that compiles to JavaScript, making it possible to write Scala programs that can run in web browsers or [[Node.js]].<ref>{{cite web|url=https://www.scala-lang.org/blog/2015/02/05/scala-js-no-longer-experimental.html |title=Scala Js Is No Longer Experimental &#124; The Scala Programming Language|date=5 February 2015 |publisher=Scala-lang.org |access-date= 28 October 2015}}</ref> 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.<ref>{{Cite web|url=https://github.com/scala-js/scala-js/releases|title=Releases · scala-js/Scala-js|website=[[GitHub]]}}</ref>
 
Scala Native is a Scala [[compiler]] that targets the [[LLVM]] compiler infrastructure to create executable code that uses a lightweight managed runtime, which uses the [[Boehm 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 than [[just-in-time compilation]] for the JVM by eliminating the initial runtime compilation of code and also providing the ability to call native routines directly.<ref>{{cite news |last=Krill |first=Paul |date=15 March 2017 |url=https://www.infoworld.com/article/3180823/application-development/scaled-down-scala-variant-cuts-ties-to-the-jvm.html |title=Scaled-down Scala variant cuts ties to the JVM |work=[[InfoWorld]] |access-date=21 March 2017}}</ref><ref>{{cite news |last=Krill |first=Paul |date=2016-05-11 |url=https://www.infoworld.com/article/3068669/application-development/scala-language-moves-closer-to-bare-metal.html |title=Scala language moves closer to bare metal |work=[[InfoWorld]]}}</ref>
Line 55 ⟶ 58:
</syntaxhighlight>
 
Unlike the [[Java (programming language)#Hello world example|stand-alone Hello World application for Java]], there is no class declaration and nothing is declared to be static.
 
When the program is stored in file ''HelloWorld.scala'', the user compiles it with the command:
Line 120 ⟶ 123:
// uses `toInt` method, declares numSquare immutable
 
import math._*
def mathFunction(num: Int) =
val numSquare = num*num
Line 136 ⟶ 139:
* The <code>return</code> 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 <code>(Type) foo</code>, Scala uses <code>foo.asInstanceOf[Type]</code>, or a specialized function such as <code>toDouble</code> or <code>toInt</code>.
* Instead of Java's <code>import foo.*;</code>, Scala uses <code>import foo._</code>.
* Function or method <code>foo()</code> can also be called as just <code>foo</code>; method <code>thread.send(signo)</code> can also be called as just <code>thread send signo</code>; and method <code>foo.toString()</code> can also be called as just <code>foo toString</code>.
 
Line 152 ⟶ 154:
{|
|- valign="top"
| <syntaxhighlight lang="java" line="1">
// Java:
public class Point {
private double x, y;
public Point(final double x, final double y) {
this.x = x;
this.y = y;
}
 
public Point(double x, double y, boolean addToGrid) {
double x, double y,
boolean addToGrid
) {
this(x, y);
 
Line 188 ⟶ 187:
}
 
double distanceToPoint(final Point other) {
return distanceBetweenPoints(x, y,
other.x, other.y);
Line 196 ⟶ 195:
 
static double distanceBetweenPoints(
final double x1, final double y1,
final double x2, final double y2) {
) {
return Math.hypot(x1 - x2, y1 - y2);
}
Line 208 ⟶ 206:
addToGrid: Boolean = false
):
import Point._*
def += (p: Point) =
Line 241 ⟶ 239:
 
== Features (with reference to Java) ==
Scala has the same compiling model as [[Java (software platform)|Java]] and [[C Sharp (programming language)|C#]], namely separate compiling and [[Java Classloaderclass loader|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.<ref name="cacm"/> In fact, Scala code can be [[Decompiler|decompiled]] to readable Java code, with the exception of certain constructor operations. To the [[Java virtual machine]] (JVM), Scala code and Java code are indistinguishable. The only difference is one extra runtime library, <code>scala-library.jar</code>.<ref>{{cite web |url=http://blog.lostlake.org/index.php?/archives/73-For-all-you-know,-its-just-another-Java-library.html |title=Home |publisher=Blog.lostlake.org |access-date=2013-06-25 |url-status=dead |archive-url=https://web.archive.org/web/20100831041226/http://blog.lostlake.org/index.php?%2Farchives%2F73-For-all-you-know%2C-its-just-another-Java-library.html |archive-date=31 August 2010}}</ref>
 
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 Java. From the Scala perspective, this is practically important because several added features in Scala are also available in C#.
Line 256 ⟶ 254:
* Method names ending in colon (<code>:</code>) expect the argument on the left-hand-side and the receiver on the right-hand-side. For example, the <code>4 :: 2 :: Nil</code> is the same as <code>Nil.::(2).::(4)</code>, 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 <code>trait FooLike { var bar: Int }</code>, an implementation may be {{code|2=scala|1=object Foo extends FooLike { private var x = 0; def bar = x; def bar_=(value: Int) { x = value {{)}}{{)}} } } }}. The call site will still be able to use a concise <code>foo.bar = 42</code>.
* The use of curly braces instead of parentheses is allowed in method calls. This allows pure library implementations of new control structures.<ref>Scala's built-in control structures such as <code>if</code> or <code>while</code> 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. [https://dl.acm.org/citation.cfm?id=2103769 Scala-Virtualized]. ''Proceedings of the ACM SIGPLAN 2012 workshop on Partial evaluation and program manipulation'', 117–120. July 2012.</ref> For example, <code>breakable { ... if (...) break() ... }</code> looks as if <code>breakable</code> was a language defined keyword, but really is just a method taking a [[Thunk (functional programming)|thunk]] argument. Methods that take thunks or functions often place these in a second parameter list, allowing to mix parentheses and curly braces syntax: <code>Vector.fill(4) { math.random }</code> is the same as <code>Vector.fill(4)(math.random)</code>. 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 <code>map</code>, <code>flatMap</code> and <code>filter</code>.
 
Line 265 ⟶ 263:
 
=== For-expressions ===
Instead of the Java "[[foreach loop|foreach]]" loops for looping through an iterator, Scala has <code>for</code>-expressions, which are similar to [[list comprehension]]s in languages such as [[Haskell]], or a combination of list comprehensions and [[Python syntax and semantics#Generator expressions|generator expression]]s in [[Python (programming language)|Python]]. For-expressions using the <code>yield</code> keyword allow a new [[collection (computer science)|collection]] 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 <code>map</code>, <code>flatMap</code> and <code>filter</code> calls. Where <code>yield</code> is not used, the code approximates to an imperative-style loop, by translating to <code>foreach</code>.
 
A simple example is:
Line 346 ⟶ 344:
 
==== Type inference ====
Due to [[type inference]], the type of variables, function return values, and many other expressions can typically be omitted, as the compiler can deduce it. Examples are <code>val x = "foo"</code> (for an immutable [[constant (programming)|constant]] or [[immutable object]]) or <code>var x = 1.5</code> (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 (programming language)|Haskell]], [[ML (programming language)|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 [[recursion (computer science)|recursive functions]]), e.g.
<syntaxhighlight lang="scala">
def formatApples(x: Int) = "I ate %d apples".format(x)
Line 360 ⟶ 358:
 
==== Anonymous functions ====
In Scala, functions are objects, and a convenient syntax exists for specifying [[anonymous function]]s. An example is the expression <{{code>|1=x => x &lt;< 2</code>}}, 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 <{{code>|2=lisp|1=(lambda (x) (&lt;< x 2))</code>}}. Note that neither the type of <code>{{mono|x</code>}} nor the return type need be explicitly specified, and can generally be inferred by [[type inference]]; but they can be explicitly specified, e.g. as <{{code>|2=scala|1=(x: Int) => x &lt;< 2</code>}} or even <{{code>|2=scala|1=(x: Int) => (x &lt;< 2): Boolean</code>}}.
 
Anonymous functions behave as true [[Closure (computer science)|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.)
Line 366 ⟶ 364:
An even shorter form of anonymous function uses [[Free variables and bound variables|placeholder]] variables: For example, the following:
 
:<{{code>|1=list map { x => sqrt(x) }</code> }}
can be written more concisely as
:<{{code>|1=list map { sqrt(_) }</code> }}
or even
:<{{code>|1=list map sqrt</code>}}
 
==== Immutability ====
Line 389 ⟶ 387:
==== Tail recursion ====
Functional programming languages commonly provide [[tail call]] optimization to allow for extensive use of [[recursion (computer science)|recursion]] without [[stack 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. [[Trampoline (computing)|Trampoline]]s have been suggested as a workaround.<ref>{{cite web|url=http://blog.richdougherty.com/2009/04/tail-calls-tailrec-and-trampolines.html|title=Rich Dougherty's blog|first=Rich|last=Dougherty|access-date=4 July 2015}}</ref> Trampoline support has been provided by the Scala library with the object <code>scala.util.control.TailCalls</code> since Scala 2.8.0 (released 14 July 2010). A function may optionally be annotated with <code>@tailrec</code>, in which case it will not compile unless it is tail recursive.<ref>{{cite web|url=https://www.scala-lang.org/api/current/scala/util/control/TailCalls$.html |title=TailCalls - Scala Standard Library API (Scaladoc) 2.10.2 - scala.util.control.TailCalls |publisher=Scala-lang.org |access-date=2013-06-25}}</ref>
 
 
An example of this optimization could be implemented using the [[factorial]] definition. For instance, the recursive version of the factorial: <syntaxhighlight lang="scala">
Line 401 ⟶ 398:
else factorial(n - 1, n * accum)
</syntaxhighlight>However, this could compromise composability with other functions because of the new argument on its definition, so it is common to use [[Closure (computer programming)|closures]] to preserve its original signature: <syntaxhighlight lang="scala" line="1">
def factorial(n: Int): Int =
 
@tailrec
def loop(current: Int, accum: Int): Int =
if ncurrent == 0 then accum
else loop(current - 1, ncurrent * accum)
loop(n, 1) // Call to the closure using the base case
Line 478 ⟶ 475:
// abstract
def draw()
 
 
class SimpleWindow extends Window:
Line 484 ⟶ 480:
println("in SimpleWindow")
// draw a basic window
 
trait WindowDecoration extends Window
 
 
trait HorizontalScrollbarDecoration extends WindowDecoration:
Line 496 ⟶ 490:
super.draw()
// now draw a horizontal scrollbar
 
trait VerticalScrollbarDecoration extends WindowDecoration:
Line 503 ⟶ 496:
super.draw()
// now draw a vertical scrollbar
 
trait TitleDecoration extends WindowDecoration:
Line 510 ⟶ 502:
super.draw()
// now draw the title bar
 
</syntaxhighlight>
Line 559 ⟶ 550:
extension (i: Int)
def isEven = i % 2 == 0
def isOdd = !i.isEven
 
import MyExtensions._* // bring implicit enrichment into scope
4.isEven // -> true
</syntaxhighlight>
Line 569 ⟶ 559:
 
== Concurrency ==
Scala's standard library includes support for [[futures and promises]], in addition to the standard Java concurrency APIs. Originally, it also included support for the [[actor model]], which is now available as a separate [[Source-available software|source-available]] platform [[Akka (toolkit)|Akka]]<ref name="AkkaAbout">[https://doc.akka.io/docs/akka/snapshot/intro/what-is-akka.html What is Akka?], Akka online documentation</ref> licensed by [[Lightbend Inc.]] Akka actors may be [[Distributed computing|distributed]] or combined with [[software transactional memory]] (''transactors''). Alternative [[communicating sequential processes]] (CSP) implementations for channel-based message passing are Communicating Scala Objects,<ref name="CSO">{{cite book |last=Sufrin |first=Bernard |date=2008 |chapter=Communicating Scala Objects |editor1-last=Welch |editor1-first=P. H. |editor2-last=Stepney |editor2-first=S. |editor3-last=Polack |editor3-first=F.A.C. |editor4-last=Barnes |editor4-first=F. R. M. |editor-last5=McEwan |editor-first5=A.A. |editor6-last=Stiles |editor6-first=G.S. |editor7-last=Broenink |editor7-first=J. F. |editor8-last=Sampson |editor8-first=A. T. |url=http://users.comlab.ox.ac.uk/bernard.sufrin/CSO/cpa2008-cso.pdf |title=Communicating Process Architectures 2008: WoTUG-31 |publisher=IOS Press |isbn=978-1586039073}}</ref> or simply via [[JCSP]].
 
An Actor is like a thread instance with a mailbox. It can be created by <code>system.actorOf</code>, overriding the <code>receive</code> method to receive messages and using the <code>!</code> (exclamation point) method to send a message.<ref>{{cite web|url=http://www.scala-tour.com/#/using-actor|title=Scala Tour|first=Kay|last=Yan|access-date=4 July 2015}}</ref>
Line 601 ⟶ 591:
 
== Cluster computing ==
The most well-known open-source cluster-computing solution written in Scala is [[Apache Spark]]. Additionally, [[Apache Kafka]], the [[Publish–subscribe pattern|publish–subscribe]] [[message queue]] popular with Spark and other stream processing technologies, is written in Scala.
 
== Testing ==
Line 978 ⟶ 968:
! scope="row" | 2.13.14<ref>{{cite web |url=https://www.scala-lang.org/news/2.13.14 |title=Scala 2.13.14 is now available! |date=2024-05-01 |access-date=2024-08-12 |website=Scala-lang.org}}</ref>
| style="text-align:right;" | 1 May 2024
| {{sdash}}
|-
! scope="row" | 32.413.015<ref>{{cite web |url=https://www.scala-lang.org/blognews/2024/02/29/scala-32.4.0-and-3.3.3-released13.html15 |title=Scala 32.413.015 andis 3.3.3 LTSnow releasedavailable! |date=2024-0209-2925 |access-date=2024-08-12-05 |website=Scala-lang.org}}</ref>
| style="text-align:right;" | 25 Sep 2024
| {{sdash}}
|-
Line 1,037 ⟶ 1,031:
| {{sdash}}
|-
! scope="row" | 3.3.3<ref name="scala-lang.org">{{cite web |url=https://www.scala-lang.org/blog/2024/02/29/scala-3.4.0-and-3.3.3-released.html |title=Scala 3.4.0 and 3.3.3 LTS released! |date=2024-02-29 |access-date=2024-08-12 |website=Scala-lang.org}}</ref>
| style="text-align:right;" | 29 February 2024
| {{sdash}}
|-
! scope="row" | 3.4.0<ref name="scala-lang.org"/>
! scope="row" | 3.4.0<ref>{{cite web |url=https://www.scala-lang.org/blog/2024/02/29/scala-3.4.0-and-3.3.3-released.html |title=Scala 3.4.0 and 3.3.3 LTS released! |date=2024-02-29 |access-date=2024-08-12 |website=Scala-lang.org}}</ref>
| style="text-align:right;" | 29 February 2024
| {{sdash}}
Line 1,059 ⟶ 1,053:
Scala is [[statically typed]], while both Groovy and Clojure are [[dynamically typed]]. This makes the type system more complex and difficult to understand but allows almost all<ref name=unsound>{{cite web|url=https://raw.githubusercontent.com/namin/unsound/master/doc/unsound-oopsla16.pdf|title=Java and Scala's Type Systems are Unsound}}</ref> 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 (programming language)|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 the [[Lisp (programming language)|Lisp]] syntax, which is different in both appearance and philosophy.{{Citation needed|date=October 2015}}
Line 1,072 ⟶ 1,066:
The Popularity of Programming Language Index,<ref name="pypl">{{cite news |title=Popularity of Programming Language Index |url=https://pypl.github.io/PYPL.html}}</ref> 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 (programming language)|Java]] and [[Kotlin (programming language)|Kotlin]], ranked 12th.
 
The [https://redmonk.com/sogrady/category/programming-languages/ RedMonk Programming Language] Rankings, which establishes rankings based on the number of [[GitHub]] projects and questions asked on [[Stack Overflow]], in January 2021 ranked Scala 14th.<ref name="redmonk2">{{cite news |last=O'Grady |first=Stephen |date=1 March 2021 |title=The RedMonk Programming Language Rankings: January 2021 |url=https://redmonk.com/sogrady/2021/03/01/language-rankings-1-21/ |website=RedMonk}}</ref> Here, Scala was placed inside a second-tier group of languages–ahead of [[Go (programming language)|Go]], [[PowerShell]], and [[Haskell (programming language)|Haskell]], and behind [[Swift (programming language)|Swift]], [[Objective-C]], [[Microsoft TypeScript|Typescript]], and [[R (programming language)|R]].
 
The [[TIOBE index]]<ref name="tiobe1"/> 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 (programming language)|Haskell]] (38th) and [[Erlang (programming language)|Erlang]], but below [[Go (programming language)|Go]] (14th), [[Swift (programming language)|Swift]] (15th), and [[Perl]] (19th).
 
{{As of|2022}}, JVM-based languages such as Clojure, Groovy, and Scala are highly ranked, but still significantly less popular than the original [[Java (programming language)|Java]] language, which is usually ranked in the top three places.<ref name="redmonk2"/><ref name="tiobe1">{{cite news|title=TIOBE Index for May 2021 |url=https://www.tiobe.com/tiobe-index/}}</ref>
Line 1,093 ⟶ 1,087:
* [[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.<ref>{{cite web|url=https://github.com/apache/kafka/tree/trunk/core/src/main/scala/kafka|title=Apache Kafka source code at GitHub|publisher=Apache Software Foundation|access-date=29 March 2023}}</ref>
* [[Gilt Groupe|Gilt]] uses Scala and [[Play Framework]].<ref>{{cite web|url=https://www.lightbend.com/blog/play_framework_akka_and_scala_at_gilt|title=Play Framework, Akka and Scala at Gilt Groupe |author=<!--Staff writer(s); no by-line.-->|date=15 July 2013|publisher=Lightbend|access-date=16 July 2016}}</ref>
* [[Foursquare (service)|Foursquare]] uses Scala and [[Lift (web framework)|Lift]].<ref>{{cite web|url=http://www.grenadesandwich.com/blog/steven/2009/11/27/scala-lift-and-future|title=Scala, Lift, and the Future|access-date=4 July 2015|url-status=deadusurped|archive-url=https://web.archive.org/web/20160113201402/http://www.grenadesandwich.com/blog/steven/2009/11/27/scala-lift-and-future|archive-date=13 January 2016}}</ref>
* [[Coursera]] uses Scala and [[Play Framework]].<ref>{{cite web |last=Saeta |first=Brennan |url=https://medium.com/coursera-engineering/why-we-love-scala-at-coursera-80fa1fc66d74 |title=Why we love Scala at Coursera |publisher=Coursera Engineering |date=2014-02-17 |access-date=2023-09-21}}</ref>
 
* [[Apple Inc.]] uses Scala in certain teams, along with Java and the Play framework.<ref>{{cite web|url=https://twitter.com/hayvok/status/705468085461889025|title=Apple Engineering PM Jarrod Nettles on Twitter|publisher=Jarrod Nettles|access-date=2016-03-11}}</ref><ref>{{cite web|url=https://alvinalexander.com/photos/30-scala-job-openings-apple|title=30 Scala job openings at Apple|publisher=Alvin Alexander|access-date=2016-03-11}}</ref>
* ''[[The Guardian]]'' newspaper's high-traffic website [[guardian.co.uk]]<ref>{{Cite news|author1=David Reid |author2=Tania Teixeira |name-list-style=amp |url=https://news.bbc.co.uk/1/hi/programmes/click_online/8537519.stm |title=Are people ready to pay for online news?|publisher=BBC |access-date=2010-02-28 |date=26 February 2010}}</ref> announced in April 2011 that it was switching from Java to Scala.<ref>{{cite web |url=http://www.h-online.com/open/news/item/Guardian-switching-from-Java-to-Scala-1221832.html |title=Guardian switching from Java to Scala |date=2011-04-05 |access-date=2011-04-05|publisher=[[Heise Online]]}}</ref><ref>{{cite web |url=https://www.infoq.com/articles/guardian_scala |title=Guardian.co.uk Switching from Java to Scala|publisher=InfoQ.com |date=2011-04-04 |access-date=2011-04-05}}</ref>
Line 1,102 ⟶ 1,095:
* Swiss bank [[UBS]] approved Scala for general production use.<ref>{{cite news |last=Binstock |first=Andrew |date=2011-07-14 |url=https://drdobbs.com/architecture-and-design/231001802 |title=Interview with Scala's Martin Odersky |work=[[Dr. Dobb's Journal]] |access-date=2012-02-10}}</ref>
* [[LinkedIn]] uses the [[Scalatra]] [[microframework]] to power its Signal API.<ref>{{cite news |last=Synodinos |first=Dionysios G. |date=2010-10-11 |url=https://www.infoq.com/articles/linkedin-scala-jruby-voldemort |title=LinkedIn Signal: A Case Study for Scala, JRuby and Voldemort |publisher=[[InfoQ]]}}</ref>
* [[Meetup (website)|Meetup]] uses Unfiltered toolkit for real-time APIs.<ref>{{cite web |url=https://making.meetup.com/post/2929945070/real-life-meetups-deserve-real-time-apis |title=Real-life Meetups Deserve Real-time APIs}}</ref>
* [[Remember the Milk]] uses Unfiltered toolkit, Scala and Akka for public API and real-time updates.<ref>{{cite web |url=https://blog.rememberthemilk.com/2011/08/real-time-updating-comes-to-the-remember-the-milk-web-app |title=Real time updating comes to the Remember The Milk web app}}</ref>
* [[Verizon]] seeking to make "a next-generation framework" using Scala.<ref>{{cite web |url=https://geniusadstech.com/what-is-scala-learn-scala/ |title=WHAT IS SCALA |date=8 March 2023 |access-date=2023-03-17}}</ref>
Line 1,121 ⟶ 1,114:
== See also ==
{{Portal|Free and open-source software|Computer programming}}
* [[SBT (software)|sbt]], a widely used build tool for Scala projects
* [[Apache Spark|Spark]] Framework is designed to handle, and process big-data and it solely supports Scala
* [[Neo4j]] is a java spring framework supported by Scala with ___domain-specific functionality, analytical capabilities, graph algorithms, and many more
Line 1,230 ⟶ 1,223:
[[Category:Statically typed programming languages]]
[[Category:Cross-platform free software]]
[[Category:Free compilers and interpretersopen source compilers]]
[[Category:Source-to-source compilers]]