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

Keep your projects up-to-date with Scala Steward

Wednesday, July 10, 2019

I’m excited to announce version 0.3 of Scala Steward and to introduce it to the Scala community! Scala Steward is a robot that helps you keep dependencies, sbt, and sbt plugins up-to-date by automatically creating pull requests on GitHub, GitLab, or Bitbucket that bump outdated version numbers.

How to use it

You can use it with any public Scala project on GitHub that uses sbt simply by adding it to this file and then wait for the first pull requests to come in a few hours later. Over 500 projects are already using this public instance of Scala Steward which I’m running as a free service for the whole Scala OSS ecosystem. Since Sep 9, 2018, when Scala Steward created its first pull request, it has created more than 11 900 pull requests of which over 8 300 are already merged!

Here is a screenshot of one of Scala Steward’s pull requests: screenshot of a Scala Steward pull request

Receiving automatic pull requests that bump versions of dependencies reduces maintenance if your code compiles without warnings and errors with the new version. In many cases, it is enough to review the changelog of the new version and to check that your automated tests pass before merging such pull requests. If you are adventurous, you can even let Scala Steward’s pull requests be merged automatically.

Running your own instance

You can also run your own instance of Scala Steward for your private repositories and join the companies that are already doing this. Unfortunately this isn’t well documented yet. Improving the documentation would make a great first contribution after you have figured out how to set it up.

Automatic code migrations with Scalafix

What if a new version of your dependencies contains breaking changes so that your code does not compile without errors or warnings anymore? In these cases automatic version bumps only notify you of a new version and make you aware that human intervention is needed to fix errors and warnings and to adapt the code to the new version.

Fortunately, we can improve on this situation by combining Scala Steward with the excellent Scalafix tool. Scalafix is a refactoring and linting tool that allows to rewrite code based on user-supplied rules. You can read more about Scalafix here and here. Scalafix rules can also be used for version migrations to help users updating to new versions and some libraries (like Cats, FS2, or http4s) are already providing such migrations. With Scala Steward, we now have the possibility to apply Scalafix migrations automatically to create pull requests like this:

diff --git a/build.sbt b/build.sbt
--- a/build.sbt
+++ b/build.sbt
 libraryDependencies := List(
-  "org.typelevel" %% "cats-core" % "0.9.0"
+  "org.typelevel" %% "cats-core" % "1.6.1"
 )

diff --git a/src/main/scala/cats.scala b/src/main/scala/cats.scala
--- a/src/main/scala/cats.scala
+++ b/src/main/scala/cats.scala
 object cats {
-  (Option(1) |@| Option(2) |@| Option(3)).map(_ + _ + _)
+  (Option(1), Option(2), Option(3)).mapN(_ + _ + _)
 }

Besides bumping the Cats version number, the Scalafix migration took care of the breaking changes that were introduced between Cats 0.9.0 and Cats 1.0.0 and updated the code so that it compiles cleanly with the new version. These automatic migrations have the potential to significantly reduce maintenance costs of version updates that contain breaking changes or deprecations.

Get involved

Scalafix migrations are great but we haven’t yet solved the problem of writing them automatically for version updates. :-) That means there are plenty of opportunities for new contributors to help library maintainers writing Scalafix migrations. And by integrating them into Scala Steward, their value is amplified by the number of projects that use Scala Steward. Even small contributions can already benefit a large chunk of the Scala ecosystem.

After you have written a Scalafix migration for your favorite library, Scala Steward needs to be made aware that it exists and for which version update it should be applied. Instructions for adding them to Scala Steward and more details about the Scalafix integration in Scala Steward can be found here. Once the migration has been added and the new version of the library is released, you can enjoy watching Scala Steward creating pull requests with changes from your Scalafix migration!

There are also enough opportunities to improve Scala Steward itself. The Scalafix integration, for example, has only been added recently and is still rough around the edges.

Recap

Scala Steward:

  • Can create automatic pull requests that bump dependency versions. This saves a lot of time.
  • In addition to the version bumps, it can migrate the code with Scalafix.
  • You can help the whole Scala ecosystem by writing Scalafix migrations.

Try out Scala Steward now!

Credits

Scala Steward wouldn’t exist without Roman Timushev’s great sbt-updates which is an integral part of Scala Steward. A special shout-out also goes to @impurepics who created the cute and iconic logo!

And many thanks to the 20+ contributors who made Scala Steward to what it is today: Alex, Anil Kumar Myla, Arulselvan Madhavan, Bayram Kiran, Cédric Chantepie, Christopher Davenport, Dale Wijnand, Daniel Pfeiffer, David Francoeur, Fabian, Filipe Regadas, Jakub Kozłowski, JCollier, Jeff Martin, kenji yoshida, Mark Canlas, Michael Wizner, Philippus Baalman, Piotr Gabara, Renato Cavalcanti, sullis, TATSUNO Yasuhiro, Thomas Heslin, and Thomas Kaliakos.

I’d also like to thank Andrea Magnorsky, David Francoeur, Lars Hupel, Seth Tisue, and Yifan Xing for proofreading this post.

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