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.1

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 Monday, June 30, 2014

Scala 2.12 will require Java 8. Here’s how we plan to make this transition as smooth as possible.

Goals

  • Minimize overhead of the transition for both users and library maintainers.
  • Continue Java 6 support for a while longer (only in Scala 2.11).
  • Track the Java platform evolution.

How

  • Upcoming 2.11.x releases will introduce the following experimental features (under a flag): Java 8-style closure compilation, Miguel’s new back-end & optimizer.
  • Hassle-free cross-building between 2.11 and 2.12 through full backward source compatibility (we won’t remove deprecated methods, but will support optional deprecation errors). Closely align 2.11 and 2.12 compiler and standard library code bases.
  • The official Scala 2.12 distribution will be built for Java 8 (and thus require it). The new back-end (and optimizer) will become the default.

Background

  • We can’t have one Scala binary version target two different Java versions without further artifactId name mangling. Even if maven did have support for specifying the required Java version, this fork would be a big burden on the eco-system. Thus, the split between required Java versions has to align with the Scala (binary) version.
  • We’ll check 2.11/2.12 cross-building by running the same community build on both versions. To improve backwards source compatibility, Scala 2.12 will not remove deprecated members. The 2.12 compiler will however (by default) emit deprecation errors for usage of members deprecated <= 2.11.0. (In principle, if we were to compile the 2.12 library for Java 6, it should be backwards binary compatible with 2.11.)
  • It’s important to keep up with the platform, even though Java 8’s MethodHandle-based support for closures may not immediately yield significant performance benefits (definitely reduces bytecode size, and thus likely compilation times, though). For platforms that don’t support Java 8 bytecode yet, two projects exist that rewrite Java 8 invokedynamic bytecode to Java 6 (retrolambda or Forax’s JSR292 backport). I’m not aware of the equivalent for default methods, but it’s feasible.

Shared features between Scala 2.11 (under a flag) & 2.12

  • Compile lambdas efficiently using method handles. (Separate compatibility module needed on 2.11 – see below.)

  • Java 8 interop (bidirectional):

    • Improve support for reading Java 8 bytecode (already in 2.11)
    • Improve and turn on SAM support by default (synthesize anonymous class java 8-style). This allows calling Java 8 higher-order methods seamlessly from Scala (already in 2.11 under -Xexperimental).
    • Compatibility module to let Java 8 call Scala higher-order methods.
  • Fully integrate Miguel’s new back-end & optimizer (refactor code, test & document in-depth, remove old back-end).

  • Style checker: an efficient, community-driven, platform for accurate coding style checking (built on top of the compiler).

  • Collections: improve test coverage, performance, documentation (& modularize?)

  • Improve documentation: focus on content. (This is a great place to start contributing, as well as on the tooling side of documentation.)

  • Continue infrastructure improvements (sbt build, improve pull request validation & release automation, bug tracker cleanup and automation).

Features exclusive to Scala 2.12: more Java 8 fun

Development of the following features starts in 2015. Since they are binary incompatible, they can’t be backported to 2.11.

  • Turn FunctionN into Functional Interfaces, so that Java 8 code can call higher-order methods in Scala without a wrapper.
  • Support for @interface traits, which are guaranteed to compile to Java interfaces (useful for interop, performance and binary compatibility). This is a generalization of the above feature.
  • Streams: integrate into Scala collections? (Anywhere from providing converters to replacing existing functionality.)
  • Use the JDK’s forkjoin library instead of embedding our own. (Switch the global default ExecutionContext to be backed by the ForkJoinPool.commonPool().)
  • SIP-20 Improved lazy val initialization (if time allows).

Timing

Scala 2.10.5 (Q4 2014) will be the last 2.10 release. We’re planning five 2.11.x releases in 2014, and a few more in 2015 (we’re still deciding on when to EOL 2.11.x). At Typesafe, 2.12 development will begin with infrastructure work in Q4 2014, with our development focus shifting to 2.12 in 2015.

2.10.004/01/2013First 2.10.x release
2.11.016/04/2014First 2.11.x release
2.11.119/05/2014
2.11.221/07/2014
2.11.329/09/2014
2.10.5Q4 2014Last 2.10.x release
2.12.0-M124/11/2014
2.11.4Dec 2014
2.12.0-M{2,3,4}Q{1,2,3} 2015quarterly 2.12.0-Mx releases
2.12.0-M5Oct 2015
2.12.0-RC1Nov 2015(1 year after M1)
2.12.0Jan 2016

During the development of Scala 2.11, we’ve made big steps forward in automating our release process and regression testing via our Community Build which builds 1M LOC of popular open source projects. Both the release script and the community builds are also run on a nightly basis.

As such, as of Scala 2.11.1, we’ve decided to skip Release Candidates for 2.x.y releases where y > 0. This enables more frequent minor releases on a predictable schedule.

(This roadmap was published on 30 June 2014.)

Recently...

date-icon Wednesday, May 21, 2014 announcement
We are very pleased to announce the release of Scala 2.11.1! Get started with the Hello Scala 2.11 template in Typesafe Activator Download a distribution...
date-icon Monday, April 21, 2014 announcement
We are very pleased to announce the final release of Scala 2.11.0! Get started with the Hello Scala 2.11 template in Typesafe Activator Download a...
date-icon Tuesday, April 08, 2014 announcement
We are very pleased to announce Scala 2.11.0-RC4, the next release candidate of Scala 2.11.0! Download it now from scala-lang.org or via Maven Central. Since...
date-icon
For more, visit our
News archive or Blog

Scala on Twitter


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