Scala runs...

  • on the JVM
  • on 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!

Effective Programming in Scala

  • 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 Chat: Hello Discord (So Long, Gitter)

Tuesday, December 21, 2021

On behalf of the Scala organization, I am pleased to announce that we have adopted Discord as our official chat platform.

Join us!

Please join us for live text-based chat on the Scala Discord server, via this link:

The server has existed for several years now and is already busy and well-established. It is actively moderated under the Scala Code of Conduct.

Popular channels on the server include #scala-users, #scala-contributors, #announcements, #jobs, #tooling, #scala-js, #scala-native, and others. New channels can be proposed on #admin.

What about Gitter?

Adopting Discord means we have moved away from Gitter. Most of our old Gitter rooms are now closed. The main room remains open, but mainly so we can help people find us on Discord.

Gitter served the Scala community extremely well for more than six years. We applaud the Gitter team for their pioneering efforts, which revolutionized public online chat for programmers. We also thank Gitter for providing us with free, high-quality service for so long.

How is Discord different?

A Discord “server” may contain many “channels”, also called rooms.

When you join a Discord server, all of the public channels on that server are immediately visible to you. Unlike Gitter, you don’t have to join each channel individually. (But you can individually mute channels that don’t interest you.)

There is a desktop client and a mobile client (for iOS and Android). Both are high quality.

Former Gitter users will notice a number of quality-of-life and user-interface improvements such as reactions and replies.

What other chat servers exist?

Scala enthusiasts might also be interested in joining the following Discord servers:

  • Scalameta: Scalameta-based tooling: Metals, Scalameta, Scalafix, Scalafmt, and Mdoc
  • Typelevel: the Typelevel ecosystem for pure-functional programming in Scala
  • ZIO: Type-safe, composable asynchronous and concurrent programming for Scala
  • Functional Programming: not Scala-specific, but includes a Scala channel

And although we have closed down all but one of the official Scala Gitter rooms, as of December 2021 there are still some active Gitter rooms out there devoted to particular libraries or topics, for example playframework/playframework.

What about non-English languages?

Our website’s community page lists chat rooms and servers for many other languages besides English. Discord, Gitter, and Telegram are all represented.

As of December 2021, the list is probably not very up-to-date. We invite the community to submit pull requests that will make it more current, one language at a time. The file to edit on GitHub is community/index.md.

Are other clients supported?

Yes, via Matrix. You can connect to #scala-lang:matrix.org over the bridge, using your Matrix client of choice (perhaps Element). Not all Discord features are supported.

How did we decide to switch to Discord?

The community discussion of record on this began in October 2019 on the following Discourse thread:

  • https://users.scala-lang.org/t/can-we-have-an-official-scala-discord-server/5157

Among the objections raised were:

  • Discord is a proprietary, closed-source platform.
  • The contents of Discord rooms are not indexed on the public web.

But in the end, Discord’s feature set and its sheer popularity decided the matter. By the time we officially switched over in December 2021, most of the community had already voted with their feet and our Discord server had become much more active than our Gitter rooms.

Slack was considered as an option, but we decided it is best suited for private companies and groups, but not so well suited for open-ended public communities like ours.

Tell us more history.

Okay, let’s take a trip down memory lane.

During Scala’s earliest days (at least since 2007, perhaps earlier), the main chat platform for Scala was IRC. In those early years, when the community was still small and there weren’t that many Scala conferences and meetups yet, the IRC channel (along with the Google Groups mailing lists) was an important place where community members got to know each other and, one might even say, became a community.

Later, the IRC channel declined in popularity. In my personal view, this was due to a lack of moderation and lack of any code of conduct. It became essential to have these once the Scala community had become larger.

The IRC channel still exists to this day, now on Libera instead of Freenode, but traffic there has slowed to a trickle in recent years.

Gitter launched in 2014 and was widely adopted by the Scala community in 2015. The major advantages of Gitter over IRC include:

  • Scrollback: you can log out, log back on, and still see what people were saying while you were away. (On IRC, this was only possible if you used special software.)
  • Markdown support, including syntax-highlighting of Scala code.
  • Messages can be edited (within a limited time frame) and deleted.
  • More features supporting effective content moderation.

Discord shares these advantages as well.

Some advantages of Gitter that Discord doesn’t share:

  • GitHub integration, including GitHub-based login. (No need to make a separate account.)
  • Easy, decentralized, room creation, with room names based on GitHub repo names, making it a no-brainer for an open source maintainer to create a room specifically for their library.

However, in recent years, the Gitter platform largely stopped advancing and eventually came to feel stale. After Gitter was acquired by GitLab in 2017, some features were added such as threading, but the implementation of threading was unpopular with users. The quality and feature set of the mobile client fell behind those of the desktop client. New Vector Limited acquired Gitter in 2020 and added Matrix support, but otherwise has not advanced the platform.

Meanwhile, Discord was becoming extremely popular in the video gaming community, then crossed over into programming communities.

Are the old Gitter rooms archived?

The main Gitter room for Scala, scala/scala remains online and searchable. We’ll probably leave it online indefinitely.

The other Gitter rooms under the scala/* organization have been deleted and their contents archived; the Scala Center retains the archives.

Credits

Salar Rahmanian created the Scala Discord server initially and administered it until recently. We are grateful to him for leading the way. Thank you, Salar!

Personally, I would also like to applaud and thank everyone who’s ever been helpful and kind to a Scala newcomer arriving in one of our chat rooms for the first time. You keep my faith in humanity alive. ❤️

Twitter Feed

See more tweets, or

Follow Scala on twitter

The Scala language is maintained by

  • Scala Center
  • Lightbend
  • VirtusLab

Scala Center is supported by

EPFL Goldman Sachs 47 Degrees Twitter Spotify Lunatech Your company