Object-Oriented Meets Functional

Have the best of both worlds. Construct elegant class hierarchies for maximum code reuse and extensibility, implement their behavior using higher-order functions. Or anything in-between.

Learn More

 

Scala began life in 2003, created by Martin Odersky and his research group at EPFL, next to Lake Geneva and the Alps, in Lausanne, Switzerland. Scala has since grown into a mature open source programming language, used by hundreds of thousands of developers, and is developed and maintained by scores of people all over the world.
Download API Docs    
Spiral
Scala
2.12.1

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.

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.

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

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()
}

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.

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);
}

In the Scala example on the left, the partition method, available on all collection types (including Array), returns two new collections of the same type. Elements from the original collection are partitioned according to a predicate, which is given as a lambda, i.e., an anonymous function. The _ stands for the parameter to the lambda, i.e., the element that is being tested. This particular lambda can also be written as (x => x.age < 18).

The same program is implemented in Java on the right.

Upcoming Events

See more events or add one to our feed

What's New

blog
date icon Monday, February 27, 2017

I am happy to announce the release of scalafix v0.3, a library and tool to rewrite Scala source code. Scalafix is developed at the Scala Center with the long-term mission to help automate the migration of between Scala versions. However, as I hope to demonstrate in this post, scalafix can be used for more than just migrating between Scala versions. Scalafix can also be used for ad-hoc library and application migrations.

Scalafix v0.3 uses the new scala.meta semantic API to provide a re-designed Rewrite and Patch API to implement custom refactorings. Let me explain what that means word by word.

Note. This is the second post on scalafix and scala.meta. You might be interested in reading the first post here.

Scala.meta semantic API

Scala.meta recently announced the first release of its semantic API. This release is the product of close collaboration for the past several months between @xeno_by at Twitter and myself at the Scala Center. The objective of the semantic API is to provide operations to query information from the compiler.

The first version of the scala.meta semantic API makes it possible to query for the resolved “symbol” of a name that appears in a Scala source file. A name is a reference to some definition, for example println or scala.Predef.println. A symbol is a unique identifier of a single definition. For example, println from the standard library has the symbol _root_.scala.Predef.println(Ljava/lang/Object;)V.. The compiler is responsible for resolving names to symbols.

Scalahost is a compiler plugin in the scala.meta project that extracts symbols from the compiler and maps them to scala.meta syntax trees. Scalahost emits the extracted symbols into a “semantic database”. The semantic database can be persisted to files on disk and loaded for later analysis. Semantic databases from different compilation units, potentially produced by different versions of the Scala compiler, can be merged. This opens possibilities for large-scale code analysis.

The introduction of the scala.meta semantic API is a game changer for scalafix. The ability to resolve names to symbols opens possibilities for many scalafix rewrites. Before we cover a few example rewrites, let’s look closer at what exactly “rewrite” means.

Rewrite: meta.Tree => Seq[Patch]

In a nutshell, a scalafix Rewrite is a scala.meta.Tree => Seq[Patch] function. The tree is backed by the scala.meta semantic API, so the rewrite is able to query for compiler information such as symbols. A scalafix Patch is a small operation that can produce a diff on a Scala source file. A patch can either be a “token patch” or a “tree patch”.

Token patches are low-level but give full control over how every detail in a source file is handled, for example formatting and comments. Example token patches are Remove(token) and AddLeft(token, toAdd: String), which removes or prepends a string to token, respectively.

Tree patches are high-level and allow the rewrite author to declaratively explain what operation to perform. An example tree patch is AddGlobalImport(importer), which adds a new import to the top of a file if it does not exist. Observe that AddGlobalImport does not worry about token-level details such as whether the user groups imports by prefix (import a.{b, c}) or not (import a.b; import a.c).

Tree and token patches build a small algebra of operations that can be composed to build complex refactorings. A challenge with composing patches is to figure out what to do on conflicts. For example, what happens when one patch renames a token while the other patch removes the same token? The current strategy in scalafix is to try and resolve as many conflicts as possible on the tree patch level. It can be harder to resolve conflicts on the token level since the original intent of the patch is lost. Unsolvable conflicts abort the refactoring. In the future, we hope to support more advanced conflict resolution strategies.

To demonstrate how rewrites are implemented with scalafix v0.3, let’s step through an example use-case.

Example: Xor to Either

The functional programming library cats migrated recently from its Xor data type to Either from the standard library. It requires a few mechanical steps to migrate code to use Either instead of Xor. For example, below is a diff that’s taken from circe’s migration to Either.

-final def either: Xor[HCursor, HCursor] = if (succeeded) Xor.right(any) else Xor.left(any)
+final def either: Either[HCursor, HCursor] = if (succeeded) Right(any) else Left(any)

For this particular rewrite, we are able to get away with only using tree patches. Replace is one tree patch that can be used to replace usage of a reference such as a type, term or a static method.

Replace(Symbol("_root_.cats.data.Xor."), q"Either")
Replace(Symbol("_root_.cats.data.Xor.Left."), q"Left")
Replace(Symbol("_root_.cats.data.Xor.Right."), q"Right")

The Symbol(_root_...data.Xor) part is the scala.meta symbol referencing the class definition of cats.data.Xor. As we saw in the either: Xor[HCursor diff above, references to Xor should become Either after the rewrite.

Symbols are normalized by default, so the cats.data.Xor.Right replace patch will handle the Xor.Right type, Xor.Right companion object as well as the Right.apply constructor method.

To introduce new imports, it’s possible to pass in additionalImports

Replace(Symbol("_root_.cats.data.XorT."), q"EitherT",
        additionalImports = List(importer"cats.data.EitherT")),

Imports can be removed with the RemoveGlobalImport patch

RemoveGlobalImport(importer"cats.data.Xor")

Nothing happens if the import does not appear in the source file. Likewise, it’s OK to add the same import twice, scalafix will de-duplicate it.

The full Xor to Either scalafix rewrite can be found here and its accompanying test suite here.

Try it out!

You can use scalafix both as a library and a tool.

The recommended way to use scalafix as a library is with the sbt-scalahost plugin. By using scalafix as a library, you have full control of how, where and when to run rewrites.

The recommended way to use scalafix as tool is the sbt-scalafix plugin. It’s possible define custom tree patches in the .scalafix.conf configuration file.

I am excited to see what applications the community can build with scala.meta and scalafix. Some promising ideas that have floated around include

  • parse and run rewrites from @deprecated warning messages. This would enable library authors to provide executable migration guides.
  • shim/cross-build libraries with similar APIs. For example, a library could be developed with the scalaz API, and use scalafix to code-generate a version of the library that uses cats instead.
  • build a code search web-interface with “jump to definition” functionality powered by the scala.meta’s semantic database (similar to sxr).
  • replace usage of any2stringadd with string interpolators or explicit .toString.
  • replace usage of scala.Seq, which can be mutable, in favor of scala.collection.immutable.Seq.

If this sounds exciting to you, join us! I am happy to answer any question in the scalafix gitter channel.

PS. I want to thank @ShaneDelmore who has provided invaluable feedback from the early days of scalafix development and come up with several brilliant ideas for scalafix use-cases.

Recently...

date-icon Wednesday, February 22, 2017 blog
This year the Scala team applied again for Google Summer of Code. Scala contributors are welcome to propose project ideas on our discussion forums! Students...
date-icon Monday, February 20, 2017 blog
The Scala Center team is happy to announce the Beta of Scastie. Aleh Aleshka (OlegYch) is the original author of this project. His goal was...
date-icon Friday, January 27, 2017 blog
On 17th January, the Scala Platform Committee had its first meeting. With it, we kicked off the creation of the Scala Platform and begin the...
date-icon
For more, visit our
News archive or Blog

Scala on Twitter