This page is no longer maintained — Please continue to the home page atwww.scala-lang.org
[2.9.0 |2.8.0 |2.7.2 |2.7.1 |2.7.0 |2.6.1 |2.6.0 |2.5.0 |2.4.0 |2.3.2 |2.3.0 |2.1.8 |2.1.7 |2.1.5 |2.0 ]
No language changes were introduced in 2.9.1, 2.9.1-1 and 2.9.2.
The Scala 2.9.0 codebase includes the following new features and changes:
Every collection may be converted into a corresponding parallel collection with the new `par` method. Parallel collections utilize multicore processors by implementing bulk operations such as `foreach`, `map`, `filter` etc. in parallel. Parallel collections are located in the package `scala.collection.parallel`.
Depending on the collection in question, `par` may require copying the underlying dataset to create a parallel collection. However, specific collections share their underlying dataset with a parallel collection, making `par` a constant time operation.
Currently available parallel collections are:
The method `seq` is used to convert from a parallel collection to a corresponding sequential collection. This method is always efficient (O(1)).
TheApp trait is a safer, more powerful alternative to the previousApplication trait, which has now been deprecated. The new recommended way to write a top-level application is like this:
object Echo extends App { println("Echo" + (args mkString " "))}Objects inheriting from the oldApplication trait were almost as convenient to write, but were not thread-safe and were often not optimized by the VM, since the application’s body was execited as part of of the object’s initialization sequence. Objects inheriting theApp trait instead make use of Scala 2.9’s delayed initialization feature to execute the whole body as part of an inheritedmain method.
Another new feature of theApp scheme is that command line arguments are now accessible via theargs value (which is inherited from traitApp)
TheDelayedInit trait provides another tool to customize initialization sequences of classes and objects. If a class or object inherits from this trait, all its initialization code is packed in a closure and forwarded as an argument to a method nameddelayedInit which is defined as an abstract method in traitDelayedInit.
Implementations ofdelayedInit have thus full freedom when to execute the initialization code. For instance, Scala’s newApp trait stores all initialization sequences in an internal buffer and executes them when the object’smain method is called.
Note that only initialization code contained in classes and objects is passed toDelayedInit; initialization code contained in traits is not affected.
Improvements in jline, the repl input handler. More robust cursor handling, bash-style ctrl-R history search, new commands like:imports,:implicits,:keybindings. On platforms with the necessary runtime support,:javap will disassemble any class including repl-defined ones. A long-running repl command can now be interrupted via ctrl-C without terminating the repl session. Improved programmability: the repl classloader exposes repl-defined classes via their given names.
Scala code can now be executed in any of the following ways:
The@strictfp annotation is now supported.
Various fixes inJavaConverters andJavaConversions for smoother interoperation.
Primitive types and their boxed versions are now implicitly converted bidirectionally.
trybodycatchhandlerfinallycleanup
Here,body andcleanup can be arbitrary expressions, andhandler can be any expression which evaluates to a valid exception handler (which is:PartialFunction[Throwable, T]).
No language changes were introduced in Scala 2.8.1.
Scala 2.8.0 is a significantly innovative release, which contains a large amount of fixes and introduces many new features:
No language changes were introduced in 2.7.3 through 2.7.7.
The Scala compiler now generates Java's generic signatures, so that Scala generics are visible to Java.
The compiler can now parse (but not translate) Java source files. This makes it possible to have mixed Java/Scala projects with recursive dependencies between them. In such a project, you can submit first all the Java and Scala sources to the Scala compiler. In a second step, the Java sources are compiled using the Scala generated .class files and the Scala sources are compiled again using the Java generated .class files.
Another major addition is the first beta version of the ScalaSwing library, which is now bundled with the distribution.
There are new implementations of collection classes, contributed by David MacIver: IntMap, LongMap, and TreeHashMap (immutable), ArrayStack and OpenHashMap (mutable).
A wildcard in a type now binds to the closest enclosing type application.
For exampleList[List[_]] is now equivalent to the existential type
List[List[t]forSome {type t }]
In version 2.7.0, the type expanded instead to
List[List[t]]forSome {type t }
The new convention corresponds exactly to the way wildcards in Java are interpreted.
The contractiveness requirement for implicit method definitions has been dropped. Instead it is checked for each implicit expansion individually that the expansion does not result in a cycle or a tree of infinitely growing types.
Scala now supportsJava generic types by default:
ArrayList<String> is translated to a generic type in Scala:ArrayList[String].ArrayList<?extends Number> is translated toArrayList[_ <: Number]. This is itself a shorthand for the existential typeArrayList[T]forSome {type T <: Number }.ArrayList is translated toArrayList[_], which is a shorthand forArrayList[T]forSome {type T }.This translation works if-target:jvm-1.5 is specified, which is the new default. For any other target, Java generics are not recognized. To ensure upgradability of Scala codebases, extraneous type parameters for Java classes under-target:jvm-1.4 are simply ignored. For instance, when compiling with-target:jvm-1.4, a Scala type such asArrayList[String] is simply treated as the unparameterized typeArrayList.
The Scala compiler generates now for every case class a companion extractor object. For instance, given the case class:
case class X(elem: String)the following companion object is generated:
object X {def unapply(x: X): Some[String] = Some(x.elem)def apply(s: String): X =new X(s)}
If the object exists already, only theapply andunapply methods are added to it.
Three restrictions on case classes have been removed:
case class Foo(x: Int)case class Bar(override val x: Int, y: Int)extends Foo(x)object testextends Application { println(Bar(1, 2).x) (Bar(1, 2): Foo)match {case Foo(x) => println(x) }}
abstract.case class Foo(x: Int)object Foo {val x = 2val y = Foo(2)}object testextends Application { println(Foo.x) println(Foo.ymatch {case Foo(x)=> x } )}
The following deprecated features have beenremoved from the standard Scala library:
| Removed | Use instead |
|---|---|
All andAllRef(object scala.Predef) | Nothing andNull (available since2.3.0) |
element andarity(class scala.Product) | productElement andproductArity |
scala.compat.Math | scala.Math |
scala.testing.UnitTest | scala.testing.SUnit |
assertNotSame andassertSame(class scala.testing.SUnit.Assert) | assertNotEq andassertEq |
scala.util.Fluid | scala.util.DynamicVariable |
Mutable variables can now be introduced by a pattern matching definition, just like values can. For example:
var (x, y) =if (positive) (1, 2)else (-1, -3)var hd :: tl = mylist
Self types can now be introduced without defining an alias name forthis. For example:
class C {type T<: Traittrait Trait {this: T=> ... }}
It is now possible to define existential types using the new keywordforSome. An existential type has the formTforSome {Q} whereQ is a sequence of value and/or type declarations. Given the class definitions
class Ref[T]abstract class Outer {type T }
one may for example write the following existential types
Ref[T]forSome {type T <: java.lang.Number }Ref[x.T]forSome {val x: Outer }
It is now possible to define lazy value declarations using the new modifierlazy.
import compat.Platform._val t0 = currentTimelazy val t1 = currentTimeval t2 = currentTimeprintln("t0 <= t2: " + (t0 <= t2))//trueprintln("t1 <= t2: " + (t1 <= t2))//false (lazy evaluation of t1)
It is now possible to declare structural types using type refinements. For example:
class File(name: String) {def getName(): String = namedef open() {/*..*/ }def close() { println("close file") }}def test(f: {def getName(): String }) { println(f.getName) }test(new File("test.txt"))test(new java.io.File("test.txt"))
for-comprehensions has been deprecated.requires clause has been deprecated; use{ self: T => ... } instead.&f for unapplied methods has been deprecated; usef _ instead.Type parameters and abstract type members can now also abstract over type constructors. This allows a more preciseIterable interface:
trait Iterable[+t] {type MyType[+t] <: Iterable[t]// MyType is a type constructordef filter(p: t => Boolean): MyType[t] =//...def map[s](f: t => s): MyType[s] =//...}abstract class List[+t]extends Iterable[t] {type MyType[+t] = List[t]}
This definition ofIterable makes explicit that mapping a function over a certain structure (e.g., aList) will yield the same structure (containing different elements).
It is now possible to initialize some fields of an object before any parent constructors are called. This is particularly useful for traits, which do not have normal constructor parameters. For example:
trait Greeting {val name: Stringval msg ="How are you, " + name}class Cextends {val name ="Bob"}with Greeting { println(msg)}
In the code above, the fieldname is initialized before the constructor ofGreeting is called. Therefore, fieldmsg in classGreeting is properly initialized to"How are you, Bob".
for-comprehensions,revisedThe syntax offor-comprehensions has been changed. For example:
for (val x <- List(1, 2, 3); x % 2 == 0) println(x)
is now written
for (x <- List(1, 2, 3)if x % 2 == 0) println(x)
Thus afor-comprehension now starts with a (possibly guarded) generator followed by one or more enumerators which can be either a (possibly guarded) generator, a guard or a local value definition.
The old syntax is still available but will be deprecated in the future.
It is now possible to define anonymous functions using underscores in parameter position. For instance, the expressions in the left column are each function values which expand to the anonymous functions on their right.
_ + 1 x => x + 1_ * _ (x1, x2) => x1 * x2(_: int) * 2 (x: int) => (x: int) * 2if (_) xelse y z =>if (z) xelse y_.map(f) x => x.map(f)_.map(_ + 1) x => x.map(y => y + 1)
As a special case, a partially unapplied method is now designatedm _ instead of the previous notation&m.
The new notation will displace the special syntax forms.m() for abstracting over method receivers and&m for treating an unapplied method as a function value. For the time being, the old syntax forms are still available, but they will be deprecated in the future.
It is now possible to use case clauses to define a function value directly for functions of arities greater than one. Previously, only unary functions could be defined that way. For example:
def scalarProduct(xs: Array[Double], ys: Array[Double]) = (0.0 /: (xs zip ys)) {case (a, (b, c)) => a + b * c }
Theprivate andprotected modifiers now accept a[this] qualifier . A definitionM which is labelledprivate[this] is private, and in addition can be accessed only from within the current object. That is, the only legal prefixes forM arethis orC.this. Analogously, a definitionM which is labelledprotected[this] is protected, and in addition can be accessed only from within the current object.
The syntax for tuples has been changed from{...} to(...) . For any sequence of typesT1, ..., Tn,
(T1, ..., Tn) is a shorthand forTuplen[T1, ..., Tn].
Analogously, for any sequence of expressions or patternsx1, ..., xn,
(x1, ..., xn) is a shorthand forTuplen(x1, ..., xn).
The primary constructor of a class can now be markedprivate orprotected . If such an access modifier is given, it comes between the name of the class and its value parameters. For example:
class C[T]private (x: T) { ... }
The support for attributes has been extended and its syntax changed . Attributes are now calledannotations. The syntax has been changed to follow Java's conventions, e.g.@annotation instead of[attribute]. The old syntax is still available but will be deprecated in the future.
Annotations are now serialized so that they can be read by compile-time or run-time tools. Classscala.Annotation has two sub-traits which are used to indicate how annotations are retained. Instances of an annotation class inheriting from traitscala.ClassfileAnnotation will be stored in the generated class files. Instances of an annotation class inheriting from traitscala.StaticAnnotation will be visible to the Scala type-checker in every compilation unit where the annotated symbol is accessed.
The implementation of subtyping has been changed to prevent infinite recursions. Termination of subtyping is now ensured by a new restriction of class graphs to be finitary .
It is now explicitly ruled out that case classes can be abstract . The specification was silent on this point before, but did not explain how abstract case classes were treated. The Scala compiler allowed the idiom.
It is now possible to give an explicit alias name and/or type for the self referencethis . For instance, in
class C { self: D=> ...}
the nameself is introduced as an alias forthis withinC and the self type ofC is assumed to beD. This construct is introduced now in order to replace eventually both the qualified this constructC.this and therequires clause in Scala.
It is now possible to combine operators with assignments . For example:
var x: int = 0x += 1
It is now possible to define patterns independently of case classes, usingunapply methods in extractor objects . Here is an example:
object Twice {def apply(x: Int): int = x*2def unapply(z: Int): Option[int] =if (z%2 == 0) Some(z/2)else None}val x = Twice(21) xmatch {case Twice(n) => Console.println(n) }// prints 21
In the example,Twice is an extractor object with two methods:
apply method is used to build even numbers.unapply method is used to decompose an even number; it is in a sense the reverse ofapply.unapply methods return option types:Some(...) for a match that suceeds,None for a match that fails. Pattern variables are returned as the elements ofSome. If there are several variables, they are grouped in a tuple.In the second-to-last line,Twice'sapply method is used to construct a numberx. In the last line,x is tested against the patternTwice(n). This pattern succeeds for even numbers and assigns to the variablen one half of the number that was tested. The pattern match makes use of theunapply method of objectTwice. More details on extractors can be found in the paper "Matching Objects with Patterns" by Emir, Odersky and Williams.
A new lightweight syntax for tuples has been introduced . For any sequence of types{T1 ,.., Tn},
{T1 ,.., Tn} is a shorthand forTuplen[T1 ,.., Tn].
Analogously, for any sequence of expressions or patternsx1,.., xn,
{x1 ,.., xn} is a shorthand forTuplen(x1 ,.., xn).
It is now possible to use methods which have more than one parameter as infix operators . In this case, all method arguments are written as a normal parameter list in parentheses. Example:
class C {def +(x: int, y: String) = ...}val c =new Cc + (1,"abc")
A new standard attributedeprecated is available . If a member definition is marked with this attribute, any reference to the member will cause a "deprecated" warning message to be emitted.
A simplified syntax for functions returningunit has been introduced . Scala now allows the following shorthands:
def f(params) | for | def f(params): unit |
def f(params) { ... } | for | def f(params): unit = { ... } |
The syntax of types in patterns has been refined . Scala now distinguishes between type variables (starting with a lower case letter) and types as type arguments in patterns. Type variables are bound in the pattern. Other type arguments are, as in previous versions, erased. The Scala compiler will now issue an"unchecked" warning at places where type erasure might compromise type-safety.
The recommended names for the two bottom classes in Scala's type hierarchy have changed as follows:
All ==> NothingAllRef ==> Null
The old names are still available as type aliases.
Protected members can now have a visibility qualifier , e.g.protected[<qualifier>]. In particular, one can now simulate package protected access as in Java writing
protected[P]def X ...
whereP would name the package containingX.
Private members of a class can now be referenced from the companion module of the class and vice versa .
The lookup method for implicit definitions has been generalized . When searching for an implicit definition matching a typeT, now are considered
T.(The second clause is more general than before). Here, a class isassociated with a typeT if it is referenced by some part ofT, or if it is a base class of some part ofT. For instance, to find implicit members corresponding to the type
HashSet[List[Int], String]
one would now look in the companion modules (aka static parts) ofHashSet,List,Int, andString. Before, it was just the static part ofHashSet.
A typed pattern match with a singleton typep.type now tests whether the selector value is reference-equal to p . For example:
val p = List(1, 2, 3)val q = List(1, 2)val r = q rmatch {case _: p.type => Console.println("p")case _: q.type => Console.println("q") }
This will match the second case and hence will print"q". Before, the singleton types were erased toList, and therefore the first case would have matched, which is non-sensical.
It is now possible to write multi-line string-literals enclosed in triple quotes . Example
"""this is a
multi-line
string literal"""No escape substitutions except for unicode escapes are performed in such string literals.
There is a new syntax for class literals : For any class typeC,classOf[C] designates the run-time representation ofC.
Scala in its second version is different in some details from the first version of the language. There have been several additions and some old idioms are no longer supported. This section summarizes the main changes.
The following three words are now reserved; they cannot be used as identifiers
implicitmatchrequires
Newlines can now be used as statement separators in place of semicolons
There are some other situations where old constructs no longer work:
Pattern matching expressions Thematch keyword now appears only as infix operator between a selector expression and a number of cases, as in:
exprmatch {case Some(x) => ...case None => ...}
Variants such asexpr.match {...} or justmatch {...} are no longer supported.
"With" in extends clauses. The idiom
class Cwith M { ... }
is no longer supported. Awith connective is only allowed following anextends clause. For instance, the line above would have to be written
class Cextends AnyRefwith M { ... }
However, assumingM is a trait , it is also legal to write
class Cextends M { ... }
The latter expression is treated as equivalent to
class Cextends Swith M { ... }
whereS is the superclass ofM.
Regular Expression Patterns The only form of regular expression pattern that is currently supported is a sequence pattern, which might end in a sequence wildcard_*. Example:
case List(1, 2, _*) => ...// will match all lists starting with 1,2
It is at current not clear whether this is a permanent restriction. We are evaluating the possibility of re-introducing full regular expression patterns in Scala.
The recommended syntax of selftype annotations has changed.
class C: Textends B { ... }
becomes
class Crequires Textends B { ... }
That is, selftypes are now indicated by the newrequires keyword. The old syntax is still available but is considered deprecated.
For-comprehensions now admit value and pattern definitions. For example:
for {val x <- List.range(1, 100)val y <- List.range(1, x)val z = x + y isPrime(z)}yield Pair(x, y)
Note the definitionval z = x + y as the third item in the for-comprehension.
The rules for implicit conversions of methods to functions have been tightened. Previously, a parameterized method used as a value was always implicitly converted to a function. This could lead to unexpected results when method arguments where forgotten. Consider for instance the statement below:
show(x.toString)
whereshow is defined as follows:
def show(x: String) = Console.println(x)Most likely, the programmer forgot to supply an empty argument list() totoString. The previous Scala version would treat this code as a partially applied method, and expand it to:
show(() => x.toString())
As a result, the address of a closure would be printed instead of the value ofs.
Scala version 2.0 will apply a conversion from partially applied method to function value only if the expected type of the expression is indeed a function type. For instance, the conversion would not be applied in the code above because the expected type ofshow's parameter isString, not a function type.
The new convention disallows some previously legal code. Example:
def sum(f: int => double)(a: int, b: int): double =if (a > b) 0else f(a) + sum(f)(a + 1, b)val sumInts = sum(x => x)// error: missing arguments
The partial application ofsum in the last line of the code above will not be converted to a function type. Instead, the compiler will produce an error message which states that arguments for methodsum are missing. The problem can be fixed by providing an expected type for the partial application, for instance by annotating the definition ofsumInts with its type:
val sumInts: (int, int) => double = sum(x => x)// OK
On the other hand, Scala version 2.0 now automatically applies methods with empty parameter lists to() argument lists when necessary. For instance, theshow expression above will now be expanded to
show(x.toString())
Scala version 2.0 also relaxes the rules of overriding with respect to empty parameter lists. The revised definition ofmatching members makes it now possible to override a method with an explicit, but empty parameter list() with a parameterless method, andvice versa. For instance, the following class definition is now legal:
class C {override def toString: String =//...}
Previously this definition would have been rejected, because thetoString method as inherited fromjava.lang.Object takes an empty parameter list.
A class parameter may now be prefixed byval orvar .
Previously, Scala had three levels of visibility:private,protected andpublic. There was no way to restrict accesses to members of the current package, as in Java. Scala 2 now defines access qualifiers that let one express this level of visibility, among others. In the definition
private[C]def f(...)
access tof is restricted to all code within the class or packageC (which must contain the definition off)
The model which details mixin composition of classes has changed significantly. The main differences are:
The new mixin model is explained in more detail in theScala Language Specification.
Views in Scala 1.0 have been replaced by the more general concept of implicit parameters
The new version of Scala implements more flexible typing rules when it comes to pattern matching over heterogeneous class hierarchies . Aheterogeneous class hierarchy is one where subclasses inherit a common superclass with different parameter types. With the new rules in Scala version 2.0 one can perform pattern matches over such hierarchies with more precise typings that keep track of the information gained by comparing the types of a selector and a matching pattern . This gives Scala capabilities analogous to guarded algebraic data types.
Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland