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

Scala community build grows to 141 projects, 2.8 million lines of code

Tuesday, January 16, 2018

We on the Scala team would like to call some attention to a lesser-known but crucial component of the development effort behind Scala. It’s called the Scala community build.

What is it?

It’s a collection of open-source Scala code that includes many of the most-used libraries in the Scala ecosystem.

But it’s more than just a big pile of code; we actually compile all of these codebases, run their test suites, and rewire their builds to depend on each other, so only freshly built code, built by freshly built Scala, is involved.

Why do we do this?

The goal is to enable Scala the language and Scala the ecosystem of libraries to evolve in tandem with each other.

Having the community build as a backstop and testbed means we can confidently assess the impact of proposed changes to the Scala language, compiler, and standard library.

Our Jenkins cluster runs the community build every day against the latest Scala nightly build.

We often also run the community build against individual pull requests in the scala/scala repo to assess the impact of the PR and detect regressions before the PR is merged.

Has it helped?

Definitely. Over the past few years, the build has often caught regressions and brought unanticipated compatibility issues to light.

During the Scala 2.12 cycle, feedback from the community build was key for guiding the work on SAMs and the new trait encoding. And, seeing what went wrong in downstream projects as the 2.12 changes went in was a major source for developing the migration guidelines in the 2.12 release notes.

In the Scala 2.13 cycle, we expect the community build to play a similar role in transitioning first our own code, then the entire open-source ecosystem, to the new collections library. We’ve also begun using it to gauge our progress on Java 9 support.

Library authors have also benefited. The community build has often provided early warning of the effects of changes to Scala or changes to other libraries. It has helped maintainers standardize their builds, keep their dependencies up-to-date, identify flaky tests, and shake out assorted other issues.

How big is it?

The community build has been growing steadily since 2013. These days it includes:

2.8 million lines of code

That’s a lot!

The build uses a custom compiler plugin to make sure that only code that is actually compiled is counted. cloc, the standard tool for counting lines of code, takes care of filtering out blank lines and comments.

141 projects

There are now 141 projects in the community build, as listed in the config file. They are: acyclic, akka, akka-contrib-extra, akka-http, akka-http-cors, akka-http-session, akka-persistence-cassandra, algebra, ammonite, argonaut, atto, autowire, base64, better-files, blaze, breeze, cachecontrol, case-app, catalysts, cats, cats-effect, circe, circe-config, conductr-lib, coursier, discipline, dispatch, doodle, elastic4s, fansi, fastparse, fs2, genjavadoc, geny, gigahorse, github4s, http4s, http4s-websocket, jackson-module-scala, jawn-fs2, jawn, json4s, kind-projector, kxbmap-configs, lagom, lift-json, lightbend-emoji, log4s, machinist, macro-compat, macro-paradise, meta-paradise, metaconfig, mima, minitest, monix, monocle, multibot, nscala-time, nyaya, paiges, paradox, parboiled, parboiled2, pcplod, play, play-doc, play-json, play-webgoat, play-ws, pprint, pureconfig, sbinary, sbt-io, sbt-librarymanagement, sbt-testng, sbt, sbt-util, scala-async, scala-collections-laws, scala-continuations, scala-debugger, scala-gopher, scala-java8-compat, scala-js, scala-json-ast, scala-logging, scala-parser-combinators, scala-partest-interface, scala-partest, scala-records, pscala-refactoring, scala-ssh, scala-stm, scala-swing, scala-xml-quote, scalacheck, scalacheck-shapeless, scalafix, scalafmt, scalaj-http, scalachess, scaladex, scalalib, scalameta, scalameter, scalamock, scalapb-lenses, scalapb, scalaprops, scalariform, scalastyle, scalatags, scalatest, scalatex, scalaz, scalikejdbc, scallop, scodec-bits, scodec, scopt, scoverage, semanticdb-sbt, shapeless, simulacrum, sjson-new, sksamuel-exts, slick, sourcecode, specs2, spire, spray-json, ssl-config, tut, twirl, twitter-util, twotails, unfiltered, upickle, utest, zinc.

Want to add your project to the community build? See our eligibility guidelines.

Learning more, getting involved

The community build is documented in a wiki. Many of the questions you might have are already answered there.

If you have a question or want to get involved in the community build or in open source work on Scala more generally, come to the Scala contributors forum or chat room.

Especially involved or specialized discussions about the community build can move to the community build’s own Gitter room and GitHub issues.

Credits

The main contributors have been myself (Seth Tisue), Adriaan Moors, Grzegorz Kossakowski, Jason Zaugg, and Toni Cunei, all of whom are current or former employees of Lightbend. Toni is also the primary author of dbuild, the meta-build tool that makes the community build possible.

The community build also couldn’t exist without continual help and advice from the maintainers of the included projects. You are marvelous!

You might also like to investigate the nascent Dotty community build and sbt community build.

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