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

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

blog
date icon Wednesday, November 30, 2016

Today we at the Scala Center are happy to annouce a new release of spores, now designed to work with Java Serialization. In the August Advisory Board meeting, IBM proposed that the Scala Center work on improving the status quo of serialization in Scala. The basic idea of the proposal was to pick up work on spores to prevent users from dealing with serialization runtime errors.

Spores

Spores, a project started in 2014 by Heather Miller and Philipp Haller, took a first step towards solving this problem.

Spores provide a way to control what a closures captures, and thus hopes to make it easier to operate with them in concurrent and distributed enviornments. The key idea is to capture more type information than a standard closure, and to use this type information to have more fine-grained control over the closures’s environment.

One creates a spore like this:

import scala.spores._
val greeting = Hello
val exampleSpore = spore {
  val capturedGreeting = greeting
  (name: String) =>
    println(s"$greeting, $name!")
}

Note that anything which the function in the spore refers to is explicitly declared after spore. Variables that are not explicitly listed here result in a compilation error. This makes it clear to developers what a function captures in its environment, and allows the spores framework to check for other properties for all of the values declared in the environment, such as that each value is able to be serialized.

Though, wait a second. Java Serialization does all of its checks at runtime. If spores use type information to figure out whether or not something can be serialized at compile time, how can this work with Java Serialization?

To achieve this, previously, spores required Scala Pickling to transitively check the entire enviornment was able to be serialized, statically, at compile-time. However, we now wish to perform this check instead for Java Serialization, as Java Serialization is most often used by developers.

The transitive checker

In order to ensure that captured types only extend Serializable, and whose members are also Serializable, spores version 0.4.1 comes with a compiler plugin that complements the spores macro library. Its goal is to transitively check that every captured variable, and all of its members, are extend Serializable and are thus serializable at compile time.

Let’s see it with an example:

class NotSerializable(val o: Object) extends Serializable

Capturing an instance of NotSerializable inside a spore that is going to be serialized crashes our program with a runtime exception. Although the class NotSerializable extends indeed java.io.Serializable, the member o of type Object does not and the JVM does not know how to serialize it.

The transitive checker makes sure that examples like the above are detected at compile-time rather than runtime.

Getting started

To add spores to your project, add the following keys to your SBT build file:

libraryDependencies += "ch.epfl.scala" %% "spores" % "0.4.1"
addCompilerPlugin("ch.epfl.scala" %% "spores-serialization" % "0.4.1")

For further information on how to use it and a specification of spores, check the docs.

Next steps

This stable release is the first step towards the spores and Spark integration. In the upcoming weeks, we will work with IBM to improve the developer experience of using spores in Spark and solve reported issues.

Recently...

date-icon Monday, November 28, 2016 blog
Today we’re happy to release our (initial) plans for the Scala Platform Process. If you’re unfamiliar with previous calls for a Scala Platform, the idea...
date-icon Thursday, November 17, 2016 blog
Two weeks ago I was in Amsterdam, where we had the Scala Symposium as part of the SPLASH conference. I gave a talk at the...
date-icon Thursday, November 03, 2016 announcement
We are very happy to announce the availability of Scala 2.12.0! Headline features The Scala 2.12 compiler has been completely overhauled to make use of...
date-icon
For more, visit our
News archive or Blog

Scala on Twitter