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 3 - A community powered release

Tuesday, September 15, 2020

Scala 3 - A community powered release

After 8 years of research, experimenting, trying out, discussing, numerous contributions from academic & community collaborators, the Dotty project will finally graduate in fall 2020, by becoming Scala 3. This blog aims to capture what it takes to coordinate the Scala 3 release efforts and to invite you to help us make it a success!

Current situation?

We are coordinating around 52 projects, between less than 20 people, spread around multiple organisations, and four months to go.

Rough categories within those 52 projects are:

  • Language features
  • Tools
  • Migration
  • Performance
  • Documentation

Project roadmaps and updates are published on Contributors discourse under the “Scala 3 release projects”; more are being published every so often. Please join the forum to share your thoughts, ideas, and learn more about each project.

Who is involved in the release?

  • Prof. Martin Odersky and his research lab (LAMP) are at the forefront and a driving force behind the development of Dotty and Scala 3 release efforts. Note: they are a team of 8 people who are not working only on Dotty, but also on their research as well as teaching obligations.

  • Scala Center, the Scala language foundation, recently stepped in as a main coordinating body for the Scala 3 release efforts and dedicated significant engineering, education, communication and project management resources. Note: The Scala Center team has 9 members, 5 of whom joined (very) recently.

  • The Scala Center Advisory Board companies are supporting the Scala 3 release in different manners & capacities. All of them shared their advice and encouraged the Scala Center to take part, and some of them (such as Lightbend, VirtusLab, Lunatech, 47 Degrees) with additional engineering resources and day-to-day logistics.

  • VirtusLab powers the efforts around Scala3Doc implementation and Metals (IDE supporting Dotty via LSP). They have also recently got involved in the compiler (porting Scala 2 backend changes into Dotty for now) and Scala Native development & maintenance (road to supporting first Scala 2.12 and eventually Dotty). VirtusLab will continue its involvement in Metals / Dotty until the very release of Dotty and later on for the foreseeable future.

  • Typelevel is coordinating with its ecosystem to strive for fully source-compatible, Dotty-native releases of all related major projects within their current major (binary compatible) lineage. In theory, any downstream applications fully within the Typelevel ecosystem should be able to update to Scala 3 as easily as updating from 2.12 to 2.13. Additionally, Cats Effect is targeting end-of-year for its 3.0 release (a major overhaul of its core semantics). This release is, itself, closely coordinated downstream, meaning that many projects in the Typelevel ecosystem will be making two major Scala 3 compatible releases around the end-of-year timeframe: one for Cats Effect 2 (source-compatible with current 2.13 versions) and one for Cats Effect 3 (which will also have 2.12 and 2.13 builds).

  • Many other orgs and individual contributors who are investing their free time, to whom we are all incredibly thankful - your enthusiasm & love for Scala is very inspiring!

Where to follow the development?

(or: the credible sources)

Scala-lang.org
Twitter: @scala_lang and @odersky
Contributors discourse
Scala Center and LAMP team members

What to expect?

We are facing a global uncertainty in all areas of our life, so setting expectations would not be reasonable, to say the least. We are, however, determined to have a Scala 3 release candidate before 2020 ends. Each contribution, good word, cheer is welcome now more than ever - and we thank you in advance for bearing with us!

What can I do today?

You can already take a look at the Migration Guide and maybe try it out or add/share your experience. If you are interested in any of the projects that appear on the Contributors forum, contact the project lead and ask him/her/them how best to use your time/expertise.

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