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

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 Monday, May 30, 2016

Part of the role of the Scala Center is to run the Advisory Board, a quarterly forum for our sponsors to discuss, guide and challenge the direction of the Scala Center and how it influences the Scala community and ecosystem.

It was never intentional, but it’s become a bit of a joke at EPFL that the “Scala Center Advisory Board” was born with an unfortunate acronym! So, when I chaired our inaugral meeting in New York two weeks ago, one of the first points I made to the attendees was that we have to exceed our acronym and earn the community’s trust and respect, ensuring we provide a worthwhile and beneficial service to all users of Scala.

This respect is not something to be assumed or taken for granted, though we have received a lot of support already from many Scala users. The Advisory Board’s legitimacy as a “guiding light” to the Scala Community is quite rightly something we should expect to be challenged on, so it is paramount that we do the best with the power we have been entrusted with.

So, what is the Advisory Board?

About the Advisory Board

The Advisory Board is a separate body from the Scala Center, much as many governments have separate legislative and executive branches: the Advisory Board makes recommendations to the Scala Center on the work we should do, but it’s the Scala Center’s job to execute those recommendations.

It currently has seven voting members: representatives from each of our six sponsors, plus Bill Venners, the community representative. Additionally the Executive Director of the Scala Center, Heather Miller, sits on the board to report on the Scala Center’s activities, and provide advice on the feasibility of the proposals under consideration, and Martin Odersky is the technical advisor to the board.

The board will meet four times a year, usually via a conference call to keep costs down, but when there’s an opportunity (hopefully at least once a year) we will hold physical meetings. We organized our first meeting to take place at Scala Days in New York, as most of the board members were attending. (Those who couldn’t be there in person this time joined the meeting over Google Hangouts.)

Before our first meeting, we were a little apprehensive - despite our preparations - about how the process would play out, but having now had our first successful meeting, we have more confidence in the format for typical meetings in the future.

How does the board work?

The main goal for each meeting is to define a set of tasks - we call these “recommendations” - for the Scala Center to undertake over the coming quarter. Each board member can submit proposals for discussion - short overviews of a change or project they would like to see the Scala Center use its resources to implement - and a few minutes (usually no more than ten) will be devoted to discussing that topic amongst the members.

An important aspect of the relationship between the Scala Center and the Advisory Board is that recommendations are not binding. This means that the Scala Center has the option to ignore recommendations, if it decides to, which may seem surprising, but is actually very important. It not only maintain independence between the two bodies, but also in ensuring that the recommendations received from the Advisory Board are within our budgetary and technical capabilities. And this is why Heather and Martin sit on the board, in a non-voting capacity: to offer advice to the members on the viability of each of the proposals under discussion, so that the debates can focus on making a coherent set of recommendations which is actually achievable.

For example, a recommendation to halve scalac compilation times may have the support of the entire Advisory Board, but the Scala Center would struggle to make it happen, so there would be little point in the Advisory Board making it a recommendation.

So the discussions we have around each proposal may more closely resemble a negotiation whereby the scope of a proposal is narrowed (or maybe widened) to garner the support necessary from the board, and confirmation from the Executive Director and Technical Advisor that the idea is viable.

Once there’s some consensus around the table, we move to vote on the proposal and have a show-of-hands to formally decide whether to adopt the proposal as a recommendation. For some proposals, we may not reach any agreement amongst the members in the time available, in which case, the chairperson may decide to defer further discussion until the next meeting, or suggest that the proposal is rewritten and resubmitted at the next meeting.

I mentioned at the beginning that it’s important for the Advisory Board to make good on its promise, but it’s just as important that we are seen to be doing so. So the whole Advisory Board process is open, and we will publish the proposals and minutes from each meeting. You will be able to see these in the Advisory Board’s Github repository in the next few days.

The First Meeting

As the process was new for all of the members and less time was available for preparing proposals, we made the concession to allow proposals to be presented at the meeting (without prior submission), but in future, we will require that proposals be submitted to the repository at least a week before the meeting to give all the members an opportunity to consider them before meeting.

During the first meeting, we also elected Seth Tisue as the secretary, and his minutes will be published in the next few days.

The meeting itself was a success! We deferred one proposal until the next meeting (which will take place in August), but adopted four others:

  • to clarify the governance of Scala, including the SIP/SLIP process,
  • to define a migration path from Scala 2.x to Dotty,
  • to create a new unpaid “publicity chair” role for the Scala Center, and
  • to ensure continuation of support of Scala.js.

Over the coming weeks, we will be taking steps to ensure these recommendations come to fruition.

It was a lot of work to get this far, but, after our first successful meeting, I’m very much looking forward to the next one!

Recently...

date-icon Monday, May 23, 2016 blog
We’re very happy to announce that the first 3 out of 4 courses in our Scala specialization have launched on Coursera! The courses available today...
date-icon Friday, May 06, 2016 blog
I have been working recently on making equality tests using == and != safer in Scala. This has led to a Language Enhancement Proposal which...
date-icon Friday, April 29, 2016 blog
At Scala Days, the Scala Center will hold its first Advisory Board meeting. The Advisory Board comprises primarily of delegates from our sponsors. But, we...
date-icon
For more, visit our
News archive or Blog

Scala on Twitter


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