Scala runs...

  • on the JVM
  • on JavaScript in your browser
  • natively with LLVM beta

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 anonymous 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

Online Courses

Functional Programming Principles in Scala

  • Free (optional paid certificate)
  • New sessions starting every 2 weeks!

Functional Program Design in Scala

  • Free (optional paid certificate)
  • New sessions starting every 2 weeks!

Parallel Programming

  • Free (optional paid certificate)
  • New sessions starting every 2 weeks!

Big Data Analysis with Scala and Spark

  • Free (optional paid certificate)
  • New sessions starting every 2 weeks!

Functional Programming in Scala Capstone

  • Free (optional paid certificate)
  • New sessions starting every 2 weeks!

Effective Programming in Scala

  • Free (optional paid certificate)
  • New sessions starting every 2 weeks!

Programming Reactive Systems

  • Free (optional paid certificate)
  • New sessions starting every 2 weeks!

Upcoming Training

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

Scala 3.1.0 released!

Thursday, October 21, 2021

Hello from the Scala 3 team! It has already been six weeks since we have announced the release candidate for the first minor version after the initial release of Scala 3. Now, after two more RCs, we can confidently promote Scala 3.1.0-RC3 to a new stable release of the language. In other words, Scala 3.1.0 is officially out!

Compatibility notice

Scala 3 follows major.minor.patch versioning scheme (unlike Scala 2, which uses epoch.major.minor). This means that this is the first minor release after Scala 3.0.0. This has the following consequences:

  • Scala 3.1 is backward binary compatible: you can use dependencies compiled with Scala 3.0 in 3.1 projects.
  • Scala 3.1 is not forward binary compatible: you cannot use dependencies compiled with Scala 3.1 in Scala 3.0 projects.

Although we cannot guarantee full source compatibility between minor versions, we have put a lot of effort into assuring that all code that was working in 3.0.2, except in some rare cases, will also work in 3.1.0. This means that if you are an application developer, you can confidently update the compiler version to take advantage of the newest improvements. You will still be able to use dependencies compiled with Scala 3.0.

If you are a library maintainer, updating to 3.1.0 will force all of your users to update to 3.1.0 as well. We understand that the current state of binary compatibility may be unsatisfactory. We are actively working on technical solutions to support forward-compatibility in 3.2.0. In the meantime, we recommend testing your library with Scala 3.1.0 and 3.0.2, but publishing it with 3.0.2. This will allow downstream users to use your library even if they can’t update to Scala 3.1.0. You can find an example of build that follows this recommendation here.

What’s new in 3.1

New experimental feature: safer exceptions

A new experimental feature that allows declaring and checking which exceptions can be thrown. It relies on the effects as implicit capabilities pattern.

You can opt-in using the following import.

import language.experimental.saferExceptions

Now it is possible to mark types with the type of exception that can be thrown during the evaluation:

def f(x: Double): Double throws LimitExceeded =
  if x < limit then f(x) else throw LimitExceeded()

You can read more in the document proposing this feature.

Efficient bytecode for matching over strings

Scala, since 3.0.0, has been able to optimize pattern matches with Int as a scrutinee type by emitting bytecode containing very efficient instructions: lookupswitch or tableswitch. Now in Scala 3.1, similar behavior was implemented for matching over String literals.

fruit match
  case "apple"  => 1
  case "orange" => 2
  case "banana" => 3
  case _        => 0

will now generate lookupswitch over hash codes of String literals instead of a chain of conditional expressions. This behavior is consistent with what Java does and more performant than the old approach.

Support for -Wconf and @nowarn

We have added a -Wconf compiler flag that allows filtering and configuring compiler warnings (silence them, or turn them into errors).

We have also brought back @nowarn annotation from Scala 2.13, originally inspired by the silencer plugin. It can be used for suppressing warnings directly in the code, in the places where they are expected to occur.

-Wconf and @nowarn work largely the same way as in Scala 2, but some filters for selecting warnings are different. For the more details see the output of -Wconf:help flag.

Simplified Manifest synthesis

For the sake of compatibility with Scala 2, the Scala 3 compiler now generates given instances for the Manifest trait. The new implementation is a slightly simplified approximation of the Scala 2 implementation. It guarantees that any of the expressions:

  • manifest[A] == manifest[B]
  • manifest[A].runtimeClass == manifest[B].runtimeClass
  • optManifest[A] == optManifest[B]
  • optManifest[A].asInstanceOf[ClassTag[A]].runtimeClass == optManifest[B].asInstanceOf[ClassTag[B]].runtimeClass

that were true in Scala 2, will also remain true when compiled with Scala 3.

Mirrors for Hierarchical Sealed Types

Consider the following sealed hierarchy:

sealed trait Top
case class Middle() extends Top with Bottom
sealed trait Bottom extends Top

Previously you would not be able to summon an instance of scala.deriving.Mirror.SumOf for Top, as its child Bottom is not a case class. In Scala 3.1 this is now possible, enabling compiletime reflection over nested hierarchies of sealed types.

The only change necessary for users is that they should now consider that one of the MirroredElemTypes for a Mirror.SumOf could also be a sum type, not just product types.

Other changes

  • Scastie was integrated into Scaladoc to make snippets interactive.
  • @experimental annotation is no longer itself experimental. The users are no longer required to use a nightly build of the compiler to be able to define experimental APIs. See more detail in the design document
  • Now TastyInspector.{inspectTastyFiles, inspectTastyFilesInJar, inspectAllTastyFiles} return a boolean value indicating whether the process succeeded
  • A Wildcard was made a subtype of Ident in the reflection API
  • TypedOrTest was added as a supertype of Typed in the reflection API
  • Unapply.apply was added to allow contruction of Unapply trees from macros
  • Unreductible match types now raise type errors
  • Scala 3.1 targets Scala.js 1.7.x+. This means that users must upgrade to Scala.js 1.7.0 or later to use Scala 3.1.

Beside that Scala 3.1.0 introduced multiple small improvements and fixed a handful of bugs. You can see the detailed changelog on GitHub.

What’s next

During the Scala 3.1.0 stabilization period, which took the last six weeks, we haven’t stopped improving the language and fixing the bugs in the compiler. You can already test the results of our work, using the published release candidate: Scala 3.1.1-RC1. The full changelog is as always available on GitHub.

You can expect the stable release of Scala 3.1.1 in early December.

Contributors

Thank you to all the contributors who made the release of 3.1.0 possible 🎉

According to git shortlog -sn --no-merges 3.0.2..3.1.0 these are:

    61  Martin Odersky
    51  tanishiking
    50  Nicolas Stucki
    39  Kacper Korban
    33  Andrzej Ratajczak
    22  Dale Wijnand
    22  Olivier Blanvillain
    21  Lukas Rytz
    17  Filip Zybała
    16  Yichen Xu
    15  Rikito Taniguchi
    14  Sébastien Doeraene
    12  Krzysztof Romanowski
    11  EnzeXing
     9  Guillaume Martres
     9  Jamie Thompson
     8  Tom Grigg
     6  Seth Tisue
     5  Alec Theriault
     4  Michał Pałka
     4  Phil
     3  Fengyun Liu
     3  Paweł Marks
     2  Vadim Chelyshov
     2  Dmitrii Naumenko
     2  Julien Richard-Foy
     2  Kevin Lee
     2  Liu Fengyun
     2  Stéphane Micheloud
     2  Tomasz Godzik
     2  Adrien Piquerez
     2  adampauls
     2  noti0na1
     1  Kai
     1  Jeremy Smith
     1  Som Snytt
     1  Anselm von Wangenheim
     1  Boris
     1  Arnout Engelen
     1  odersky
     1  Anatolii Kmetiuk
     1  PJ Fanning
     1  Matthieu Bovel
     1  Performant Data
     1  Mario Bucev
     1  Ruslan Shevchenko

Library authors: Join our community build

Scala 3 has a set of widely-used community libraries that are built against every nightly Scala 3 snapshot. 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
  • VirtusLab

Scala Center is supported by

EPFL Goldman Sachs 47 Degrees Twitter Spotify Lunatech Your company