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

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!

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

Build code analyzers with Scalameta and Scalafix

Friday, November 16, 2018

We are excited to announce the release of Scalameta v4.0.0 and Scalafix v0.9.0 introducing new APIs enabling more advanced source code analysis. Scalameta is a library to read, analyze, transform and generate Scala programs. Scalafix is a refactoring and linting tool.

This release is the result of a close collaboration between the Scala Center and Twitter along with contributions from over 30 contributors in the community. Big thanks to everybody who made this happen!

In this post, we cover some exciting aspects of this release.

  • new documentation for getting started with Scalameta and Scalafix
  • the ability to query information about Scala and Java symbols on the classpath.
  • the ability to inspect synthetics generated by the compiler such as inferred type parameters and implicits.
  • how the community is sharing Scalafix rules for linting code and migrating between library versions.

Get started with the new documentation

A big focus of this release has been documentation. Scalameta and Scalafix have new websites with guides, cookbooks and reference documents.

Visit scalameta.org to see the new Scalameta documentation. Key pages of the site include:

  • SemanticDB specification: learn the details of the new semantic API.
  • SemanticDB guide: get started with the SemanticDB command-line tools metac, metacp and metap.
  • Trees guide: learn how to parse, construct, traverse and transform Scala syntax trees.
  • ScalaFiddle playground: explore Scalameta APIs directly in the browser with access to code completions and fast edit/compile/run feedback. Big thanks to scalafiddle.io for providing a great service!

Visit scalacenter.github.io/scalafix to see the new Scalafix documentation. Key pages of the site include:

We hope the new documentation helps more people join the effort in building developer tools for Scala.

Query information about Scala and Java symbols

A highlight of this release is the new ability to query information about Scala and Java symbols on the classpath. Symbol information includes the symbol’s kind (class/trait/object), properties (final/implicit/sealed), signature (method parameters/class declarations), annotations (@inline) and access modifiers (private/protected).

In Scalameta, symbol information is documented in the SemanticDB specification. SemanticDB is a data model for semantic information such as symbols and types about programs in Scala and Java. SemanticDB decouples production and consumption of semantic information, establishing documented means for communication between tools.

The SemanticDB specification contains dedicated sections for Scala symbols and Java symbols with relevant hyperlinks to respective language specifications. The SemanticDB specification also contains detailed code examples illustrating how Scala and Java language features map into SemanticDB data structures.

In Scalafix, there is a library API to query information about SemanticDB symbols. The SymbolInformation cookbook includes small recipes for how to perform a range of tasks such as listing the parameters of a method or finding all supertypes of a class.

Inspect inferred implicits and inferred type parameters

A new feature in this release is Synthetic, a data structure that encodes trees that do not appear in the original source code but are added by the compiler. Examples of synthetics include inferred type parameters, implicit arguments, or desugarings of for comprehensions.

In Scalameta, synthetics are documented in the SemanticDB specification. In Scalafix, there is a library API to inspect synthetics via the .synthetic extension method. For example, the code Some(1) has a synthetic *.apply[Int] where * represents the original Some tree node and apply resolves to the symbol scala/Option.apply().. Consult the new SemanticTree docs to learn more about using synthetics in the Scalafix API.

Synthetics were contributed by Max Ovsiankin during his internship at Twitter this summer. Max did a great job and synthetics represent only a fraction of his contributions this summer.

Share your code analyzer

A new functionality in this release is the ability to easily install and run custom Scalafix rules. For sbt users, custom rules can be installed with the scalafixDependencies setting and discovered from the sbt shell via tab completions.

// build.sbt
scalafixDependencies in ThisBuild += "org.http4s" %% "http4s-scalafix" % "0.20.0-M3"

sbt shell tab completion for Scalafix rules

For rule authors, a Scalafix rule is published to Maven Central as an ordinary library.

Within a day after the Scalafix release, Eugene Yokota had already published a Scalafix rule NoInfer.

Julien Tournay has also shared Scalafix migration rewrites for Scio v0.7, a Scala library from Spotify for Apache Beam and Google Cloud Dataflow.

Alessandro Marrella also contributed migration rewrites for http4s, a typeful, functional, streaming HTTP library for Scala.

We hope that Scalafix rules will help reduce the pain when upgrading library dependencies with breaking changes.

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