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    

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!

& Distribution

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


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.

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] = ???
import static scala.collection.JavaConversions.asJavaCollection;

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

    public void sortAuthors(List<Author> authors) {

    public void displaySortedAuthors(File file) {
        List<Author> authors = loadAuthorsFromFile(file);
        for (Author author : authors) {
                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.

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.

abstract class Spacecraft {
  def engage(): Unit
trait CommandoBridge extends Spacecraft {
  def engage(): Unit = {
    for (_ <- 1 to 3)
  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.

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)
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)

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

date icon Wednesday, February 03, 2016

What do you get if you boil Scala on a slow flame and wait until all incidental features evaporate and only the most concentrated essence remains? After doing this for 8 years we believe we have the answer: it’s DOT, the calculus of dependent object types, that underlies Scala.

A paper on DOT will be presented in April at Wadlerfest, an event celebrating Phil Wadler’s 60th birthday. There’s also a prior technical report (From F to DOT) by Tiark Rompf and Nada Amin describing a slightly different version of the calculus. Each paper describes a proof of type soundness that has been machine-checked for correctness.

The DOT calculus

A calculus is a kind of mini-language that is small enough to be studied formally. Translated to Scala notation, the language covered by DOT is described by the following abstract grammar:

Value       v  =  (x: T) => t            Function
                  new { x: T => ds }     Object

Definition  d  =  def a = t              Method definition
                  type A = T             Type

Term        t  =  v                      Value
                  x                      Variable
                  t1(t2)                 Application
                  t.a                    Selection
                  { val x = t1; t2 }     Local definition

Type        T  =  Any                    Top type
                  Nothing                Bottom type
                  x.A                    Selection
                  (x: T1) => T2          Function
                  { def a: T }           Method declaration
                  { type T >: T1 <: T2 } Type declaration
                  T1 & T2                Intersection
                  { x => T }             Recursion

The grammar uses several kinds of names:

x      for (immutable) variables
a      for (parameterless) methods
A      for types

The full calculus adds to this syntax formal typing rules that assign types T to terms t and formal evaluation rules that describe how a program is evaluated. The following type soundness property was shown with a mechanized, (i.e. machine-checked) proof:

If a term t has type T, and the evaluation of t terminates, then the result of the evaluation will be a value v of type T.


Formulating the precise soundness theorem and proving it was unexpectedly hard, because it uncovered some technical challenges that had not been studied in depth before. In DOT - as well as in many programming languages - you can have conflicting definitions. For instance you might have an abstract type declaration in a base class with two conflicting aliases in subclasses:

 trait Base { type A }
 trait Sub1 extends Base { type A = String }
 trait Sub2 extends Base { type A = Int }
 trait Bad extends Sub1 with Sub2

Now, if you combine Sub1 and Sub2 in trait Bad you get a conflict, since the type A is supposed to be equal to both String and Int. If you do not detect the conflict and assume the equalities at face value you get String = A = Int, hence by transitivity String = Int! Once you are that far, you can of course engineer all sorts of situations where a program will typecheck but cause a wrong execution at runtime. In other words, type soundness is violated.

Now, the problem is that one cannot always detect these inconsistencies, at least not by a local analysis that does not need to look at the whole program. What’s worse, once you have an inconsistent set of definitions you can use these definitions to “prove” their own consistency - much like a mathematical theory that assumes true = false can “prove” every proposition including its own correctness.

The crucial reason why type soundness still holds is this: If one compares T with an alias, one does so always relative to some path x that refers to the object containing T. So it’s really x.T = Int. Now, we can show that during evaluation every such path refers to some object that was created with a new, and that, furthermore, every such object has consistent type definitions. The tricky bit is to carefully distinguish between the full typing rules, which allow inconsistencies, and the typing rules arising from runtime values, which do not.

Why is This Important?

There are at least four reasons why insights obtained in the DOT project are important.

  1. They give us a well-founded explanation of nominal typing. Nominal typing means that a type is distinguished from others simply by having a different name. For instance, given two trait definitions

      trait A extends AnyRef { def f: Int }
      trait B extends AnyRef { def f: Int }

    we consider A and B to be different types, even though both traits have the same parents and both define the same members. The opposite of nominal typing is structural typing, which treats types that have the same structure as being the same. Most programming languages are at least in part nominal whereas most formal type systems, including DOT, are structural. But the abstract types in DOT provide a way to express nominal types such as classes and traits. The Wadlerfest paper contains examples that show how one can express classes for standard types such as Boolean and List in DOT.

  2. They give us a stable basis on which we can study richer languages that resemble Scala more closely. For instance, we can encode type parameters as type members of objects in DOT. This encoding can give us a better understanding of the interactions of subtyping and generics. It can explain why variance rules are the way they are and what the precise typing rules for wildcard parameters [_ <: T], [_ >: T] should be.

  3. DOT also provides a blueprint for Scala compilation. The new Scala compiler dotty has internal data structures that closely resemble DOT. In particular, type parameters are immediately mapped to type members, in the way we propose to encode them also in the calculus.

  4. Finally, the proof principles explored in the DOT work give us guidelines to assess and treat other possible soundness issues. We now know much better what conditions must be fulfilled to ensure type soundness. This lets us put other constructs of the Scala language to the test, either to increase our confidence that they are indeed sound, or to show that they are unsound. In my next blog I will present some of the issues we have discovered through that exercise.


date-icon Monday, January 11, 2016 blog
SIP/SLIP meeting, January 2016 A video recording of this meeting is available. Welcomes and apologies Today we have @SethTisue, @sjrd, @heathermiller, @non and @odersky January...
date-icon Saturday, January 02, 2016 blog
For most of us, the change of the year is an occasion for thinking about what we missed doing last year and where we want...
date-icon Wednesday, December 09, 2015 announcement
With 2016 rapidly approaching, it’s time for an update on our plans for Scala next year! Scala 2.11: We expect to conclude the 2.11.x series with...
For more, visit our
News archive or Blog

Scala on Twitter

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