Object-Oriented Meets Functional

Have the best of both worlds. Construct elegant class hierarchies for maximum code reuse and extensibility, implement their behavior using higher-order functions. Or anything in-between.

Learn More

 

Scala began life in 2003, created by Martin Odersky and his research group at EPFL, next to Lake Geneva and the Alps, in Lausanne, Switzerland. Scala has since grown into a mature open source programming language, used by hundreds of thousands of developers, and is developed and maintained by scores of people all over the world.
Download API Docs    
Spiral
Scala
2.11.6

Scala in a Nutshell

 click the boxes below to see Scala in action! 

Seamless Java Interop

Scala runs on the JVM, so Java and Scala stacks can be freely mixed for totally seamless integration.

Type Inference

So the type system doesn’t feel so static. Don’t work for the type system. Let the type system work for you!

Concurrency
& Distribution

Use data-parallel operations on collections, use actors for concurrency and distribution, or futures for asynchronous programming.

Traits

Combine the flexibility of Java-style interfaces with the power of classes. Think principled multiple-inheritance.

Pattern Matching

Think “switch” on steroids. Match against class hierarchies, sequences, and more.

Higher-Order Functions

Functions are first-class objects. Compose them with guaranteed type safety. Use them anywhere, pass them to anything.

Author.scala
class Author(val firstName: String,
    val lastName: String) extends Comparable[Author] {

  override def compareTo(that: Author) = {
    val lastNameComp = this.lastName compareTo that.lastName
    if (lastNameComp != 0) lastNameComp
    else this.firstName compareTo that.firstName
  }
}

object Author {
  def loadAuthorsFromFile(file: java.io.File): List[Author] = ???
}
App.java
import static scala.collection.JavaConversions.asJavaCollection;

public class App {
    public List<Author> loadAuthorsFromFile(File file) {
        return new ArrayList<Author>(asJavaCollection(
            Author.loadAuthorsFromFile(file)));
    }

    public void sortAuthors(List<Author> authors) {
        Collections.sort(authors);
    }

    public void displaySortedAuthors(File file) {
        List<Author> authors = loadAuthorsFromFile(file);
        sortAuthors(authors);
        for (Author author : authors) {
            System.out.println(
                author.lastName() + ", " + author.firstName());
        }
    }
}

Combine Scala and Java seamlessly

Scala classes are ultimately JVM classes. You can create Java objects, call their methods and inherit from Java classes transparently from Scala. Similarly, Java code can reference Scala classes and objects.

In this example, the Scala class Author implements the Java interface Comparable<T> and works with Java Files. The Java code uses a method from the companion object Author, and accesses fields of the Author class. It also uses JavaConversions to convert between Scala collections and Java collections.

Type inference
scala> class Person(val name: String, val age: Int) {
     |   override def toString = s"$name ($age)"
     | }
defined class Person

scala> def underagePeopleNames(persons: List[Person]) = {
     |   for (person <- persons; if person.age < 18)
     |     yield person.name
     | }
underagePeopleNames: (persons: List[Person])List[String]

scala> def createRandomPeople() = {
     |   val names = List("Alice", "Bob", "Carol",
     |       "Dave", "Eve", "Frank")
     |   for (name <- names) yield {
     |     val age = (Random.nextGaussian()*8 + 20).toInt
     |     new Person(name, age)
     |   }
     | }
createRandomPeople: ()List[Person]

scala> val people = createRandomPeople()
people: List[Person] = List(Alice (16), Bob (16), Carol (19), Dave (18), Eve (26), Frank (11))

scala> underagePeopleNames(people)
res1: List[String] = List(Alice, Bob, Frank)

Let the compiler figure out the types for you

The Scala compiler is smart about static types. Most of the time, you need not tell it the types of your variables. Instead, its powerful type inference will figure them out for you.

In this interactive REPL session (Read-Eval-Print-Loop), we define a class and two functions. You can observe that the compiler infers the result types of the functions automatically, as well as all the intermediate values.

Concurrent/Distributed
val x = future { someExpensiveComputation() }
val y = future { someOtherExpensiveComputation() }
val z = for (a <- x; b <- y) yield a*b
for (c <- z) println("Result: " + c)
println("Meanwhile, the main thread goes on!")

Go Concurrent or Distributed with Futures & Promises

In Scala, futures and promises can be used to process data asynchronously, making it easier to parallelize or even distribute your application.

In this example, the future{} construct evaluates its argument asynchronously, and returns a handle to the asynchronous result as a Future[Int]. For-comprehensions can be used to register new callbacks (to post new things to do) when the future is completed, i.e., when the computation is finished. And since all this is executed asynchronously, without blocking, the main program thread can continue doing other work in the meantime.

Traits
abstract class Spacecraft {
  def engage(): Unit
}
trait CommandoBridge extends Spacecraft {
  def engage(): Unit = {
    for (_ <- 1 to 3)
      speedUp()
  }
  def speedUp(): Unit
}
trait PulseEngine extends Spacecraft {
  val maxPulse: Int
  var currentPulse: Int = 0
  def speedUp(): Unit = {
    if (currentPulse < maxPulse)
      currentPulse += 1
  }
}
class StarCruiser extends Spacecraft
                     with CommandoBridge
                     with PulseEngine {
  val maxPulse = 200
}

Flexibly Combine Interface & Behavior

In Scala, multiple traits can be mixed into a class to combine their interface and their behavior.

Here, a StarCruiser is a Spacecraft with a CommandoBridge that knows how to engage the ship (provided a means to speed up) and a PulseEngine that specifies how to speed up.

Pattern matching
// Define a set of case classes for representing binary trees.
sealed abstract class Tree
case class Node(elem: Int, left: Tree, right: Tree) extends Tree
case object Leaf extends Tree

// Return the in-order traversal sequence of a given tree.
def inOrder(t: Tree): List[Int] = t match {
  case Node(e, l, r) => inOrder(l) ::: List(e) ::: inOrder(r)
  case Leaf          => List()
}

Switch on the structure of your data

In Scala, case classes are used to represent structural data types. They implicitly equip the class with meaningful toString, equals and hashCode methods, as well as the ability to be deconstructed with pattern matching.

In this example, we define a small set of case classes that represent binary trees of integers (the generic version is omitted for simplicity here). In inOrder, the match construct chooses the right branch, depending on the type of t, and at the same time deconstructs the arguments of a Node.

Go Functional with Higher-Order Functions

In Scala, functions are values, and can be defined as anonymous functions with a concise syntax.

Scala
val people: Array[Person]

// Partition `people` into two arrays `minors` and `adults`.
// Use the higher-order function `(_.age < 18)` as a predicate for partitioning.
val (minors, adults) = people partition (_.age < 18)
Java
List<Person> people;

List<Person> minors = new ArrayList<Person>(people.size());
List<Person> adults = new ArrayList<Person>(people.size());
for (Person person : people) {
    if (person.getAge() < 18)
        minors.add(person);
    else
        adults.add(person);
}

In the Scala example on the left, the partition method, available on all collection types (including Array), returns two new collections of the same type. Elements from the original collection are partitioned according to a predicate, which is given as a lambda, i.e., an anonymous function. The _ stands for the parameter to the lambda, i.e., the element that is being tested. This particular lambda can also be written as (x => x.age < 18).

The same program is implemented in Java on the right.

Upcoming Events

See more events or add one to our feed

What's New

announcement
date icon Tuesday, May 05, 2015

We are very pleased to announce the release of Scala 2.12.0-M1!

Code that compiles on 2.11.x without deprecation warnings should compile on 2.12.x (we do not guarantee this for experimental APIs, such as reflection). If not, please file an issue.

We are working with the community to ensure availability of the core projects of the Scala 2.12 eco-system. This release is not binary compatible with the 2.11.x series, to allow us to keep improving the Scala standard library.

The Scala 2.12 series targets Java 8. Programs written in Scala 2.12, including the Scala 2.12 compiler, can only be executed on Java 8 or newer. Note that the current milestone release (2.12.0-M1) still targets Java 6.

New Features in the 2.12 Series

Scala 2.12 contains all of the bug fixes and improvements made in the 2.11 series.

At the current stage in the milestone cycle, Scala 2.12 is still very similar to Scala 2.11.

The following changes are planned for Scala 2.12:

  • Java 8 style closures. The Scala compiler will emit closure classes (lambdas) in the same manner as Java 8. The design notes for this feature are available in this gist.
  • Lambda syntax for SAM types. Similar to Java 8, Scala 2.12 allows instantiating any type with one single abstract method by passing a lambda. This feature is already avalable in Scala 2.11 using the -Xexperimental compiler option. It improves the experience of using libraries written for Java 8 in Scala.
  • New backend and optimizer. The “GenBCode” backend, which is already available in Scala 2.11 using the -Ybackend:GenBCode compiler option, will be enabled by default. Scala 2.12 will also ship with a new inliner and bytecode optimizer. We keep track of issues and work items for the new optimizer on the scala-opt repostiory issue tracker.

The above list is incomplete and will be extended during the Scala 2.12 milestone cycle.

Up the current milestone, the Scala team and contributors fixed 47 bugs that are exclusive to Scala 2.12.0. During the development cycle of Scala 2.12, we will continue to backport issues to 2.11 whenever feasible. With the release of 2.12.0, backports to 2.11 will be dialed back.

Removed Modules

The following modules have been removed from the Scala 2.12 distribution:

  • The Scala actors library is no longer released with Scala 2.12. We recommend that you use the Akka actors library instead. To migrate your code, follow the Scala actors migration guide before upgrading your project to Scala 2.12.
  • The Scala distribution archives and the scala-library-all maven dependency no longer inlcude Akka actors. To use the Akka actors library, add it to your project as a dependency.
  • The continuations plugin is no longer shipped with the Scala 2.12 distribution.

Contributors

A big thank you to everyone who’s helped improve Scala by reporting bugs, improving our documentation, spreading kindness in mailing lists and other public fora, and submitting and reviewing pull requests! You are all magnificent.

According to git shortlog -sn --no-merges 2.11.x..v2.12.0-M1, 33 people contributed to this major release: Jason Zaugg, Lukas Rytz, A. P. Marki, Rex Kerr, Kato Kazuyoshi, Max Bileschi, jxcoder, François Garillot, rubyu, Adriaan Moors, Dominik Gruntz, Evgeny Vereshchagin, Marc Siegel, Masato Sogame, Simon Ochsenreither, Todd Vierling, Viktor Klang, cchantep, Denton Cockburn, Paolo Giarrusso, Denis Rosset, Roman Hargrave, Rui Gonçalves, Shadaj, harryhuk, Steven Scott, Antoine Gourlay, Aleksandar Prokopec, Lukas Elmer, Erlend Hamnaberg, Maks Atygaev, Malte Isberner, dgruntz. Thank you!

These release notes are hosted on GitHub and are continuously updated during the Scala 2.12.0 release cycle. You are kindly invited to contribute!

Reporting Bugs

Please file any bugs you encounter on our issue tracker. If you’re unsure whether something is a bug, please contact the scala-user mailing list. Before creating a new issue, search search the issue tracker to see if your bug has already been reported.

Scala IDE for Eclipse

A release of the Scala IDE for Eclipse for Scala 2.12 will be available together with the release.

Note that for the current milestone (2.12.0-M1), the Scala IDE is not yet available.

Available Projects

Please refer to the list of libraries and frameworks available for Scala 2.12.

Binary Compatibility

Since Sala 2.11, minor releases of Scala are binary compatible. Scala 2.12 continues this tradition: every 2.12.x release will be binary compatible with 2.12.0. Note that milestone releases and release candidates are not binary compatible with any other release.

Definition

When two versions of Scala are binary compatible, it is safe to compile your project on one Scala version and link against another Scala version at run time. Safe run-time linkage (only!) means that the JVM does not throw a (subclass of) LinkageError when executing your program in the mixed scenario, assuming that none arise when compiling and running on the same version of Scala. Concretely, this means you may have external dependencies on your run-time classpath that use a different version of Scala than the one you’re compiling with, as long as they’re binary compatibile. In other words, separate compilation on different binary compatible versions does not introduce problems compared to compiling and running everything on the same version of Scala.

We check binary compatibility automatically with MiMa.

Forwards and Back

We distinguish forwards and backwards compatibility (think of these as properties of a sequence of versions, not of an individual version). Maintaining backwards compatibility means code compiled on an older version will link with code compiled with newer ones. Forwards compatibility allows you to compile on new versions and run on older ones.

Thus, backwards compatibility precludes the removal of (non-private) methods, as older versions could call them, not knowing they would be removed, whereas forwards compatibility disallows adding new (non-private) methods, because newer programs may come to depend on them, which would prevent them from running on older versions (private methods are exempted here as well, as their definition and call sites must be in the same compilation unit).

Meta

Note that so far we’ve only talked about the jars generated by scalac for the standard library and reflection. Our policies do not extend to the meta-issue: ensuring binary compatibility for bytecode generated from identical sources, by different version of scalac? (The same problem exists for compiling on different JDKs.) While we strive to achieve this, it’s not something we can test in general. Notable examples where we know meta-binary compatibility is hard to achieve: specialisation and the optimizer.

In short, if binary compatibility of your library is important to you, use MiMa to verify compatibility before releasing. Compiling identical sources with different versions of the Scala compiler (or on different JVM versions!) could result in binary incompatible bytecode. This is rare, and we try to avoid it, but we can’t guarantee it will never happen.

Concretely

We guarantee forwards and backwards compatibility of the "org.scala-lang" % "scala-library" % "2.12.x" and "org.scala-lang" % "scala-reflect" % "2.12.x" artifacts, except for anything under the scala.reflect.internal package, as scala-reflect is still experimental. We also strongly discourage relying on the stability of scala.concurrent.impl and scala.reflect.runtime, though we will only break compatibility for severe bugs here.

Recently...

By
Vojin Jovanovic
date-icon Monday, March 16, 2015 news
This year the Scala team applied again for Google Summer of Code, and we’re happy to announce that we have been approved to be mentoring...
date-icon Thursday, March 05, 2015 announcement
We are very pleased to announce the availability of Scala 2.11.6! Get started with the Hello Scala 2.11 template in Typesafe Activator Download a distribution...
date-icon Thursday, March 05, 2015 announcement
With pride and a pang of nostalgia, we announce the availability of Scala 2.10.5 – the last release in the 2.10.x series. We’d like to...
date-icon
For more, visit our
News archive or Blog

Scala on Twitter


 
See more tweets, or
Follow Scala on Twitter
white Twitter logo