Scala runs on...

  • JVM
  • 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!

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 2 community build reaches goals

Thursday, February 20, 2020

The Scala 2 community build is a large collection of open-source Scala code that we build and run every day in order to validate changes to the Scala compiler and standard library.

If you’re not familiar with the community build at all, this introduction, from January 2018, still applies.

A year ago, we updated you on improvements made up through January 2019. The post you are reading highlights the progress the community build has made since then.

In short, we believe the Scala 2 community build is now essentially complete. Still, we will continue to run and maintain it throughout Scala 2’s lifetime.

We describe the build as complete because:

  • It has successfully supported the release of Scala 2.13 and the migration of the ecosystem to 2.13.
  • It is large and diverse enough to support future 2.13.x releases.
  • It is now entirely green on JDK 8 and 11 and nearly green on JDK 14.

Details below.

Overall growth

The 2.13 community build is now the main one. (The 2.11 and 2.12 builds still exist, but they have required only light maintenance for some time now.)

The 2.13 build currently has 209 repos and a total of 3.4 million lines of code. (A year ago the main build was the 2.12 one, with 185 repos and 3.2 million lines. 2.13 was still catching up, at only 79 repos.)

It takes about nine hours to run.

Repos added in the last year include: advxml, akka-http-webgoat, akka-management, akka-streams-tcp-chat, alpakka-kafka, avro4s, cats-effect-testing, cats-mtl, cats-retry, cats-testkit-scalatest, cats-time, circe-generic-extras, circe-jackson, ciris, claimant, context-applied, discipline-scalatest, discipline-specs2, doobie, droste, expression-evaluator, fastparse-scalameta, finagle, http4s-jwt-auth, implicitbox, jwt-scala, kits, libra, log4cats, mdoc, meow-mtl, mockito-scala, munit, natchez, pfps-shopping-cart, play-file-watch, playframework, prog-scala-examples, quicklens, redis4cats, scala-collection-contrib, scala-collection-laws, scala-hedgehog, scala-parallel-collections, scala-pet-store, scala-typed-holes, scalatestplus-junit, scalatestplus-mockito, scalatestplus-scalacheck, scalatestplus-testng, scodec-cats, sconfig, skunk, splain, squants, sttp-model, treehugger, tsec, unique, vault, verify.

See also the full list of all included repos.

Success of the Scala 2.13 series

The Scala open-source ecosystem has almost universally adopted Scala 2.13. Libraries and tools unavailable for 2.13 are few and far between, as this short list shows.

Most projects needed only minor changes around the edges to cross-compile against 2.11, 2.12, and 2.13. (Most maintainers have already dropped 2.10 from their cross-builds. Some are dropping 2.11, now, too.)

Not many new bugs were reported in Scala 2.13 itself, so without urgent fixes to ship, we’ve been able to do followup releases on a fairly leisurely schedule: 2.13.1 after three months, and 2.13.2 (coming soon) after a further six months.

We take the relative scarcity of new defects as evidence that the community build is providing a high level of quality assurance. The build can’t catch everything, but it has prevented many regressions from ever being released.

JDK 11 and 14

The 2.13 build is now 100% green on JDK 11. That’s because:

  • Support for JDK 11 in Scala and sbt has improved.
  • Across the Scala and Java ecosystems, maintainers have increasingly added JDK 11 to their own CI matrices.
  • We report JDK 11 related issues to upstream maintainers.

We also now run the build on an early-access build of JDK 14. Only two repos currently fail (for minor reasons not having to do with regressions in Scala).

All variants of the community build now run on AdoptOpenJDK. This seems to be an increasingly standard choice, within Lightbend and in the community at large.

Maintenance and process changes

The way the community build is configured and maintained has been overhauled. It is now easier for us to maintain, and it is easier for the maintainers of included repos to participate. If interested, see this post for details.

The future: Scala 2

We believe that for Scala 2, the community build is now essentially complete. It is sufficiently large, and sufficiently up-to-date with the ecosystem, to serve the needs of ongoing development on the Scala 2.13.x series. We will keep maintaining it indefinitely, but we don’t expect any further really notable changes or expansions.

(What about Scala 2.14? We don’t expect any 2.14 release to be needed. If you missed that news, see this blog post from December.)

The future: Scala 3

And what about Scala 3? Dotty has its own community build, and it continues to grow. It now contains 25 repos, compared to 5 a year ago.

Here is the list of included repos. If you want to add something, there are instructions.

Credits

I (Seth Tisue) am the primary maintainer of the Scala community build, as a member of the Scala team at Lightbend. Toni Cunei, also at Lightbend, is the primary author of dbuild, the meta-build tool that makes the community build possible.

The community build couldn’t exist without continual help and advice from the maintainers of the included projects.

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