Scala runs on...

  • JVM
  • JavaScript in your browser

- with more backends on the way. -

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.

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

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.

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.

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.

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

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

Run Scala in your browser

Scastie is Scala + SBT in your browser! You can use any version of Scala, or even alternate backends such as Dotty, Scala.js, Scala Native, and Typelevel Scala. You can use any published library. You can save and share Scala programs/builds with anybody.

Run Scala code interactively

Scala ecosystem

The Scala Library Index (or Scaladex) is a representation of a map of all published Scala libraries. With Scaladex, a developer can now query more than 175,000 releases of Scala libraries. Scaladex is officially supported by Scala Center.

The Scala Library Index

What’s New

BLOG

Announcing Dotty 0.2.0-RC1, with new optimizations, improved stability and IDE support

Wednesday, July 12, 2017

Today, we are excited to release Dotty version 0.2.0-RC1. This release serves as a technology preview that demonstrates new language features and the compiler supporting them.

This release is based on the previous milestone. The highlights of this release are:

  • substantial improvement of quality of generated code for pattern matching
  • improvements in VS Code IDE stability
  • support Windows in VS Code IDE
  • improved compatibility with scalac
  • initial support for reproducible builds

This is our second scheduled release according to our 6-week release schedule.

What’s in the 0.2.0-RC1 technology preview?

The previous technology preview has shipped new language features planned for Scala 3:
Intersection Types, Union Types, Trait Parameters, Enumerations, Algebraic Data Types, By-Name Implicits.

This technology preview is geared towards improving stability and reliability. It includes:

Better generated code:

As was spotted by @gkossakowski in the previous release Dotty was on par with Scala 2.11 in speed. But why is that? The reason is that Dotty compiled by Dotty had really horrible code generated for pattern matching.

Let’s illustrate on a simple example:

case class CC(a: Int, b: Object)

  def foo(x: Any): Int = {
    val (a, b) = x match {
      case CC(s @ 1, CC(t, _)) =>
        (s , 2)
      case _ => (42, 43)
    }
    a + b
  }
  
  def booleans(a: Object) = {
    val (b1, b2) = (a.isInstanceOf[CC], a.isInstanceOf[List[Int]])
    (b1, b2) match {
      case (true, true) => true
      case (false, false) => true
      case _ => false
    }
  }

The Dotty that was released in the previous milestone didn’t contain any optimizations and generated inefficient code for it. The java-with-goto code below is equivalent to what Dotty generated.

// output of dotc 0.1.2-RC1
    public int foo(Object x) {
        var3_2 = x;
        if (!(var3_2 instanceof CC)) ** GOTO lbl-1000
        var4_3 = (CC)var3_2;
        if (CC$.MODULE$.unapply((CC)var3_2) == null) ** GOTO lbl-1000
        var5_4 = CC$.MODULE$.unapply((CC)var3_2);
        s = var5_4._1();
        var7_6 = var5_4._2();
        if (1 != s) ** GOTO lbl-1000
        var8_7 = s;
        if (!(var7_6 instanceof CC)) ** GOTO lbl-1000
        var9_8 = (CC)var7_6;
        if (CC$.MODULE$.unapply((CC)var7_6) != null) {
            var10_9 = CC$.MODULE$.unapply((CC)var7_6);
            var11_10 = var10_9._2();
            v0 = Tuple2..MODULE$.apply((Object)BoxesRunTime.boxToInteger((int)1), (Object)BoxesRunTime.boxToInteger((int)2));
        } else lbl-1000: // 5 sources:
        {
            v0 = Tuple2..MODULE$.apply((Object)BoxesRunTime.boxToInteger((int)42), (Object)BoxesRunTime.boxToInteger((int)43));
        }
        var2_11 = v0;
        a = BoxesRunTime.unboxToInt((Object)var2_11._1());
        b = BoxesRunTime.unboxToInt((Object)var2_11._2());
        return a + b;
    }

    public boolean booleans(Object a) {
        Tuple2 tuple2 = Tuple2..MODULE$.apply((Object)BoxesRunTime.boxToBoolean((boolean)(a instanceof CC)), (Object)BoxesRunTime.boxToBoolean((boolean)(a instanceof List)));
        boolean b1 = BoxesRunTime.unboxToBoolean((Object)tuple2._1());
        boolean b2 = BoxesRunTime.unboxToBoolean((Object)tuple2._2());
        Tuple2 tuple22 = Tuple2..MODULE$.apply((Object)BoxesRunTime.boxToBoolean((boolean)b1), (Object)BoxesRunTime.boxToBoolean((boolean)b2));
        Option option = Tuple2..MODULE$.unapply(tuple22);
        if (!option.isEmpty()) {
            Tuple2 tuple23 = (Tuple2)option.get();
            boolean bl = BoxesRunTime.unboxToBoolean((Object)tuple23._1());
            boolean bl2 = BoxesRunTime.unboxToBoolean((Object)tuple23._2());
            if (bl) {
                boolean bl3 = bl;
                if (bl2) {
                    boolean bl4 = bl2;
                    return true;
                }
            }
        }
        Option option2 = Tuple2..MODULE$.unapply(tuple22);
        if (option2.isEmpty()) return false;
        Tuple2 tuple24 = (Tuple2)option2.get();
        boolean bl = BoxesRunTime.unboxToBoolean((Object)tuple24._1());
        boolean bl5 = BoxesRunTime.unboxToBoolean((Object)tuple24._2());
        if (bl) return false;
        boolean bl6 = bl;
        if (bl5) return false;
        boolean bl7 = bl5;
        return true;
    }

Due to the new optimizing pattern matcher, Dotty now is able to generate the code below without -optimise

// output of 0.2.0-RC1 without -optimise
    public int foo(Object x) {
        var3_2 = x;
        if (!(var3_2 instanceof CC)) ** GOTO lbl-1000
        var4_3 = CC$.MODULE$.unapply((CC)var3_2);
        s = var5_4 = var4_3._1();
        if (1 == var5_4 && (var7_6 = var4_3._2()) instanceof CC) {
            t = CC$.MODULE$.unapply((CC)var7_6)._1();
            v0 = Tuple2..MODULE$.apply((Object)BoxesRunTime.boxToInteger((int)1), (Object)BoxesRunTime.boxToInteger((int)2));
        } else lbl-1000: // 2 sources:
        {
            v0 = Tuple2..MODULE$.apply((Object)BoxesRunTime.boxToInteger((int)42), (Object)BoxesRunTime.boxToInteger((int)43));
        }
        var2_8 = v0;
        a = BoxesRunTime.unboxToInt((Object)var2_8._1());
        b = BoxesRunTime.unboxToInt((Object)var2_8._2());
        return a + b;
    }

    public boolean booleans(Object a) {
        Tuple2 tuple2 = Tuple2..MODULE$.apply((Object)BoxesRunTime.boxToBoolean((boolean)(a instanceof CC)), (Object)BoxesRunTime.boxToBoolean((boolean)(a instanceof List)));
        boolean b1 = BoxesRunTime.unboxToBoolean((Object)tuple2._1());
        boolean b2 = BoxesRunTime.unboxToBoolean((Object)tuple2._2());
        Tuple2 tuple22 = Tuple2..MODULE$.apply((Object)BoxesRunTime.boxToBoolean((boolean)b1), (Object)BoxesRunTime.boxToBoolean((boolean)b2));
        if (tuple22 != null) {
            boolean bl;
            boolean bl2 = BoxesRunTime.unboxToBoolean((Object)tuple22._1());
            if (!bl2) {
                bl = bl2;
            } else {
                if (BoxesRunTime.unboxToBoolean((Object)tuple22._2())) {
                    return true;
                }
                bl = bl2;
            }
            if (!bl) {
                if (false != BoxesRunTime.unboxToBoolean((Object)tuple22._2())) return false;
                return true;
            }
        }
        return false;
    }

You can clearly see that it’s shorter ;-) and it actually does less work. If you additionally enable local optimizations, you get decent generated code:

// output of 0.2.0-RC1 with -optimise

    public int foo(Object x) {
        int n;
        Tuple2 tuple2;
        CC cC;
        Object object;
        if (x instanceof CC && 1 == (n = (cC = (CC)x)._1()) && (object = cC._2()) instanceof CC) {
            ((CC)object)._1();
            tuple2 = new Tuple2((Object)BoxesRunTime.boxToInteger((int)1), (Object)BoxesRunTime.boxToInteger((int)2));
        } else {
            tuple2 = new Tuple2((Object)BoxesRunTime.boxToInteger((int)42), (Object)BoxesRunTime.boxToInteger((int)43));
        }
        Tuple2 tuple22 = tuple2;
        return BoxesRunTime.unboxToInt((Object)tuple22._1()) + BoxesRunTime.unboxToInt((Object)tuple22._2());
    }

    public boolean booleans(Object a) {
        boolean bl = a instanceof CC;
        boolean bl2 = a instanceof List;
        new Tuple2((Object)BoxesRunTime.boxToBoolean((boolean)bl), (Object)BoxesRunTime.boxToBoolean((boolean)bl2));
        new Tuple2((Object)BoxesRunTime.boxToBoolean((boolean)bl), (Object)BoxesRunTime.boxToBoolean((boolean)bl2));
        if (bl && bl2) {
            return true;
        }
        boolean bl3 = bl;
        if (bl3) return false;
        if (bl2) return false;
        return true;
    }

This code still has a major inefficiency; it allocates tuples. We plan to continue the migration of local optimizations from the Dotty Linker that should allow us to generate code that is as good the code generated by the Dotty Linker with global analysis disabled:

  // output of Dotty linker https://github.com/dotty-linker/dotty/tree/opto
    public int foo(Object x) {
         CC cC;
         int n = 0;
         int n2 = 0;
         if (x instanceof CC && 1 == (cC = (CC)x)._1() && cC._2() instanceof CC) {
             n = 1;
             n2 = 2;
         } else {
             n = 42;
             n2 = 43;
         }
         return n + n2;
     }
 
     public boolean booleans(Object a) {
         boolean bl = a instanceof CC;
         boolean bl2 = a instanceof List;
         if (bl && bl2 || !bl && !bl2) {
             return true;
         }
         return false;
 }

How can you try it out?

We ship with tools that help you try out the Dotty platform:

You have several alternatives; use the sbt-dotty plugin, get a standalone installation, or try it online on Scastie.

sbt

Using sbt 0.13.13 or newer, do:

sbt new lampepfl/dotty.g8

This will setup a new sbt project with Dotty as compiler. For more details on using Dotty with sbt, see the example project.

Standalone installation

Releases are available for download on the Releases section of the Dotty repository: https://github.com/lampepfl/dotty/releases

We also provide a homebrew package that can be installed by running:

brew install lampepfl/brew/dotty

In case you have already installed Dotty via brew, you should instead update it:

brew upgrade dotty

Scastie

Scastie, the online Scala playground, supports Dotty. You can try it out there without installing anything.

What are the next steps?

Over the coming weeks and months, we plan to work on the following topics:

If you want to get your hands dirty with any of this, now is a good moment to get involved! Join the team of contributors, including Martin Odersky (@odersky) Dmitry Petrashko (@DarkDimius), Guillaume Martres (@smarter), Felix Mulder (@felixmulder), Nicolas Stucki (@nicolasstucki), Liu Fengyun (@liufengyun), Olivier Blanvillain (@OlivierBlanvillain), and others!

Library authors: Join our community build

Dotty now has a set of libraries that are built against every nightly snapshot. Currently this includes scalatest, squants and algebra. Join our community build to make sure that our regression suite includes your library.

To get started, see https://github.com/lampepfl/dotty.

Twitter Feed

See more tweets, or

Follow Scala on twitter

The Scala language is maintained by

  • Scala Center
  • Lightbend

Scala Center is supported by

EPFL IBM Verizon Goldman Sachs 47 Degrees SAP Twitter Your company