Scala (programming language)
≈ 14 min read
Names in other languages
No names in other languages are held for this entry yet.
Article bodies are English and are not machine-translated. A name in another language is not a translation of the article.
Scala ( ) is a strongly statically typed high-level general-purpose programming language that supports both object-oriented programming and functional programming. Designed to be concise, many of Scala's design decisions are intended to address criticism of Java. Scala source code can be compiled to JVM 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 using Clang. When running on the JVM, Scala provides language interoperability with Java so that libraries written in either language may be referenced directly in Scala or Java code. Like Java, Scala is object-oriented, and uses a syntax termed curly-brace which is similar to the language C. Scala 3 added an option to use the off-side rule (indenting) to structure blocks, and its use is advised. Martin Odersky has said that this turned out to be the most productive change introduced in Scala 3. Unlike Java, Scala has many features of functional programming languages (like Scheme, Standard ML, and Haskell), including currying, immutability, lazy evaluation, and pattern matching.…
Scala ( ) is a strongly statically typed high-level general-purpose programming language that supports both object-oriented programming and functional programming. Designed to be concise, many of Scala's design decisions are intended to address criticism of Java. Scala source code can be compiled to JVM 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 using Clang. When running on the JVM, Scala provides language interoperability with Java so that libraries written in either language may be referenced directly in Scala or Java code. Like Java, Scala is object-oriented, and uses a syntax termed curly-brace which is similar to the language C. Scala 3 added an option to use the off-side rule (indenting) to structure blocks, and its use is advised. Martin Odersky has said that this turned out to be the most productive change introduced in Scala 3. Unlike Java, Scala has many features of functional programming languages (like Scheme, Standard ML, and Haskell), including currying, immutability, lazy evaluation, and pattern matching. It also has an advanced type system supporting algebraic data types, covariance and contravariance, higher-order types (but not higher-rank types), anonymous types, operator overloading, optional parameters, named parameters, raw strings, and an experimental exception-only version of algebraic effects that can be seen as a more powerful version of Java's checked exceptions. The name Scala is a portmanteau of scalable and language, signifying that it is designed to grow with the demands of its users. @main def main() = println("Hello, World!") Unlike the 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: $ 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 as Apache Ant. A shorter version of the "Hello World" Scala program is: println("Hello, World!") Scala includes an interactive shell and scripting support. Saved in a file named HelloWorld2.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: $ scala Welcome 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> In Scala it is possible to define operators by using symbols as method names. In place of addPoint , the Scala example defines += , which is then invoked with infix notation as grid += this . Default visibility in Scala is public . 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. 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 { var bar: Int } , 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 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 { ... if (...) break() ... } looks as if breakable was a language defined keyword, but really is just a method taking a thunk 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 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 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. val s = for (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) (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 (mention, times) Expression (mention, times) <- mentions is an example of pattern matching (see below). Iterating over a map returns a set of key-value tuples, 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. 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. def printValue(x: String): Unit = println("I ate a %s".format(x)) or equivalently (with type inference, and omitting the unnecessary newline): def printValue(x: String) = println("I ate a %s" format x) 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 val x = "foo" (for an immutable constant or immutable object) 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, 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 then 1 else x * factorial(x - 1) An example of this optimization could be implemented using the factorial definition. For instance, the recursive version of the factorial: def factorial(n: Int): Int = if n == 0 then 1 else n * factorial(n - 1) Could be optimized to the tail recursive version like this: @tailrec def factorial(n: Int, accum: Int): Int = if n == 0 then accum else factorial(n - 1, n * accum) However, this could compromise composability with other functions because of the new argument on its definition, so it is common to use closures to preserve its original signature: def factorial(n: Int): Int = @tailrec def loop(current: Int, accum: Int): Int = if current == 0 then accum else loop(current - 1, current * accum) loop(n, 1) // Call to the closure using the base case end factorial This ensures tail call optimization and thus prevents a stack overflow error. def qsort(list: List[Int]): List[Int] = list match case Nil => Nil case pivot :: tail => val (smaller, rest) = tail.partition(_ 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 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. 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 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 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"-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.) try ... catch case nfe: NumberFormatException => { println(nfe); List(0) } case _ => Nil 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 can be written thus: val qsort: List[Int] => List[Int] = case Nil => Nil case pivot :: tail => val (smaller, rest) = tail.partition(_ 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. (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[Int] = List(2, 5, 6, 9) abstract class Window: // abstract def draw() class SimpleWindow extends Window: def draw() println("in SimpleWindow") // draw a basic window trait WindowDecoration extends Window trait HorizontalScrollbarDecoration extends WindowDecoration: // "abstract override" is needed here for "super()" to work because the parent // function is abstract. If it were concrete, regular "override" would be enough. abstract override def draw() println("in HorizontalScrollbarDecoration") super.draw() // now draw a horizontal scrollbar trait VerticalScrollbarDecoration extends WindowDecoration: abstract override def draw() println("in VerticalScrollbarDecoration") super.draw() // now draw a vertical scrollbar trait TitleDecoration extends WindowDecoration: abstract override def draw() println("in TitleDecoration") super.draw() // now draw the title bar 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, 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, 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. object MyExtensions: extension (i: Int) def isEven = i % 2 == 0 def isOdd = !i.isEven 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. val echoServer = actor(new Act: become: case msg => println("echo " + msg) ) 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, Scala also supports asynchronous programming with software transactional memory, and event streams.
Text derived from https://en.wikipedia.org/w/index.php?oldid=1376488172 under CC BY-SA 4.0; modifications have been made.