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.5.0-RC1

Friday, December 1, 2017

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

If you’re not familiar with Dotty, it’s a platform to try out new language concepts and compiler technologies for Scala. The focus is mainly on simplification. We remove extraneous syntax (e.g. no XML literals), and try to boil down Scala’s types into a smaller set of more fundamental constructs. The theory behind these constructs is researched in DOT, a calculus for dependent object types. You can learn more about Dotty on our website.

This is our fifth scheduled release according to our 6-week release schedule. The previous technology preview added support for Scala 2.12 and came with a brand new REPL.

What’s new in the 0.5.0-RC1 technology preview?

Reworked implicit search #3421

The treatment of ambiguity errors has changed. If an ambiguity is encountered in some recursive step of an implicit search, the ambiguity is propagated to the caller. Example: Say you have the following definitions:

class A
class B extends C
class C
implicit def a1: A
implicit def a2: A
implicit def b(implicit a: A): B
implicit def c: C

and the query implicitly[C].

This query would now be classified as ambiguous. This makes sense, after all there are two possible solutions, b(a1) and b(a2), neither of which is better than the other and both of which are better than the third solution, c. By contrast, Scala 2 would have rejected the search for A as ambiguous, and subsequently have classified the query b(implictly[A]) as a normal fail, which means that the alternative c would be chosen as solution!

Scala 2’s somewhat puzzling behavior with respect to ambiguity has been exploited to implement the analogue of a “negated” search in implicit resolution, where a query Q1 fails if some other query Q2 succeeds and Q1 succeeds if Q2 fails. With the new cleaned up behavior these techniques no longer work. But there is now a new special type scala.implicits.Not which implements negation directly. For any query type Q: Not[Q] succeeds if and only if the implicit search for Q fails.

Dependent function types #3464

A dependent function type describes functions where the result type may depend on the function’s parameter values. Example:

class Entry { type Key; key: Key }

def extractKey(e: Entry): e.Key = e.key          // a dependent method
val extractor: (e: Entry) => e.Key = extractKey  // a dependent function value

Scala already has dependent methods, i.e. methods where the result type refers to some of the parameters of the method. Method extractKey is an example. Its result type, e.key refers its parameter e (we also say, e.Key depends on e). But so far it was not possible to turn such methods into function values, so that they can be passed as parameters to other functions, or returned as results. Dependent methods could not be turned into functions simply because there was no type that could describe them.

In Dotty this is now possible. The type of the extractor value above is

(e: Entry) => e.Key

This type describes function values that take any argument x of type Entry and return a result of type x.Key.

TASTY frontend

TASTY is a new serialization format for typed syntax trees of Scala programs. When compiled by Dotty, a program classfile will include its TASTY representation in addition to its bytecode.

The TASTY frontend uses ASTs from the TASTY in classfiles as input instead of source files. There are currently two backends using the TASTY frontend:

  • A Dotty class file decompiler that let you decompile code previously compiled to TASTY:

    dotc -decompile -classpath <classpath> <classname>
    
  • A Dotty TASTY compiler that will recompile code previously compiled to TASTY:

    dotc -from-tasty -classpath <classpath> <classname>
    

    This is the first step toward linking and whole world optimisations, recompiling code to a different backends…

Generic java signatures #3234

Dotty now emits generic signatures for classes and methods. Theses signatures are used by compilers, debuggers and to support runtime reflection. For example:

scala> class Foo[T, U]
// defined class Foo
scala> classOf[Foo[_, _]].getTypeParameters.map(_.getName).mkString(", ")
val res0: String = "T, U"

Trying out Dotty

Scastie

Scastie, the online Scala playground, supports Dotty. This is an easy way to try Dotty without installing anything.

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.

IDE support

It is very easy to start using the Dotty IDE in any Dotty project by following the IDE guide.

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

Let us know what you think!

If you have questions or any sort of feedback, feel free to send us a message on our Gitter channel. If you encounter a bug, please open an issue on GitHub.

Contributing

Thank you to all the contributors who made this release possible!

According to git shortlog -sn --no-merges 0.4.0-RC1..0.5.0-RC1 these are:

   112  Nicolas Stucki
   108  Martin Odersky
    33  Allan Renucci
    18  Guillaume Martres
    17  Martin Duhem
    13  liu fengyun
     9  Miron Aseev
     4  Matt D'Souza
     4  Raphael Bosshard
     2  k0ala
     2  Vitor Vieira
     2  Fengyun Liu
     2  Michal Gutowski
     2  Robert Soeldner
     2  Aurélien Richez
     1  rsoeldner
     1  Hermes Espínola González
     1  Jean Detoeuf
     1  Karol Chmist
     1  Olivier Blanvillain
     1  William Narmontas
     1  Yevgen Nerush
     1  gan74
     1  gosubpl

If you want to get your hands dirty and contribute to Dotty, now is a good time to get involved! You can have a look at our Getting Started page for new contributors, the Awesome Error Messages project or some of the simple Dotty issues. They make perfect entry-points into hacking on the compiler.

We are looking forward to having you join the team of contributors.

Library authors: Join our community build

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

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