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)
  • 18 Feb 2019

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

Write Scala in VS Code, Vim, Emacs, Atom and Sublime Text with Metals

Tuesday, April 16, 2019

We are excited to announce the release of Metals v0.5. Metals is a Scala language server that supports code completions, type at point, goto definition, fuzzy symbol search and other advanced code editing and navigation capabilities.

Metals can be used in VS Code, Vim, Emacs, Atom and Sublime Text as well as any other Language Server Protocol compatible editor. Metals works with sbt, Gradle, Maven and Mill thanks to Bloop, a fast Scala build server. Adding support for other build tools is possible through the Build Server Protocol.

Metals is developed at the Scala Center along with contributors from the community.

Features

In this post we are going to demonstrate how to use Metals with VS Code. To get started, install the Scala (Metals) extension on the VS Code Marketplace and open an sbt project directory. The Metals extension will prompt you to import the build.

Import sbt build

The build import step can take a while to run and once complete, you can enjoy the features of Metals.

Diagnostics

Syntax errors update as you type and type errors are published on file save.

A separate bloop command-line interface can be installed to test and run programs from a terminal using the same compilation artifacts as Metals.

Type at point

Hover over an identifier to see its expression type, symbol signature and documentation.

Type at point

Observe how the active expression is highlighted as the cursor moves.

Code completions

As you type, code completions are suggested for a range of use-cases such as overriding a method from a superclass or generating an exhaustive pattern match for a sealed type.

Code completions

Observe that imports are automatically inserted as you complete symbols that are not present in the scope.

Parameter hints

When writing arguments for a method call, use parameter hints to see the method signature and available method overloads.

Parameter hints

Goto definition

Jump to symbol definitions in your project sources and Scala/Java library dependencies.

Goto definition

Find references

Find all usages of a symbol in the workspace, including implicits and apply methods.

Find references

And more

Visit the Metals documentation to learn more about other supported features. The website also includes instructions for how to use Metals with the editors Vim, Emacs, Atom and Sublime Text. However, note that the best supported editor is VS Code.

Collaboration with VirtusLab

As part of a new collaboration between the Scala Center and VirtusLab, VirtusLab will be contributing engineers to work on Metals over the coming months. The VirtusLab engineers Marek Żarnowski (@marek1840) and Tomasz Godzik (@tgodzik) have already contributed several impressive pull requests:

  • textDocument/foldingRange (#632): code folding that understands Scala syntax.
  • textDocument/documentHighlight (#621): highlight occurrences of a symbol in the current file.
  • textDocument/completion (#640): override def completions without the need to type “override def “.

It is our pleasure to welcome Marek and Tomasz to the team and we look forward to working together with them to improve the Scala code editing experience.

Future work

Metals currently does not support several common IDE features:

  • Refactorings such as rename symbol, add missing import, add inferred result type, move class, extract value.
  • Running a main function or unit test with attached debugger.
  • Triggering code completions, type at point and goto definition in *.sbt files.
  • Working with hybrid *.scala and *.java projects, although you can try using the Eclipse Java Language Server for editing *.java only projects.

Metals may not be a good fit if you frequently rely on these features. You might want to try IntelliJ IDEA instead, which has great Scala support and implements all of the features listed above.

Share your feedback

Please give Metals a try and share your feedback on Gitter or by reporting issues to the Metals GitHub repository.

Credits

Code completions, type at point and parameter hints are implemented using the Scala presentation compiler, which is maintained by the Scala compiler team at Lightbend.

Metals started as a fork of the dragos-vscode-scala repository in late 2017 and has since then grown into a project with over 40 contributors: Ólafur Páll Geirsson, Gabriele Petronella, Alexey Alekhin, Marek Żarnowski, Iulian Dragos, JesusMtnez, Johan Muedsam, Ben Hutchison, Jonathan Shen, Martin Duhem, PanAeon, Ayoub Benali, Gabriel Volpe, Shane Delmore, Tomasz Godzik, fc, Carlo Sana, Jakub Kozłowski, Eugene Melekhov, Jesús Martínez, Corey O’Connor, Eugene Burmako, Pavel Logvinov, Yashwanth Yadavalli, Arnout Engelen, Carlos Quiroz, Chris, Cody Allen, David Strawn, Edoardo Vacchi, Eric Peters, Evgeniy Tokarev, Joe Ferris, Jozef Koval, Martijn Hoekstra, Michael Pollmeier, Rory Graves, Ross A. Baker, Tim Nieradzik, Alexandre Archambault, keiSunagawa.

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