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

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 Thursday, February 05, 2015

Today, we announced the release of Scala.js v0.6.0, the Scala to JavaScript compiler, and dropped the experimental flag associated to it. Yes, you read it right: Scala.js is no longer experimental! After exactly 2 years of development, we finally feel comfortable calling it production-ready.

Note, however, that Scala.js is not part of the Typesafe Reactive platform. Thus, although we consider Scala.js production-ready, Typesafe does not provide any commercial support for it.

More than a compiler, an entire ecosystem

At its core, Scala.js is a compiler from Scala to JavaScript. It compiles .scala files to a single optimized and minimized .js file per application. The resulting JavaScript code is vanilla ECMAScript 5.1, which therefore works everywhere – on any OS, any browser, or even on Node.js. Just like regular Scala, you get all the powerful language features that you know and love: type inference, classes, traits and objects, pattern matching, the collections library, implicits, etc. And, in the same way that Scala is fully interoperable with Java, Scala.js is fully interoperable with JavaScript. Scala.js can interoperate with JavaScript either in a statically or dynamically-typed way.

While that all sounds great, a compiler would be nothing without an ecosystem of libraries and tools. Scala.js has that covered too!

You can use your favorite IDE to develop in Scala.js, and from experience, we can report that IntelliJ IDEA and Eclipse both provide a flawless development experience. Other editors should also work well. With Scala.js tooling, you get syntax highlighting, code completion (even for JavaScript libraries and the DOM!), jump-to-definition, and most other features you come to expect in a Scala tooling environment. After all, Scala.js is just Scala. Though, your IDE won’t be able to run or debug Scala.js code. For that, you can use a browser, and you can even step through your Scala code because Scala.js emits source maps.

Building Scala.js libraries and applications is easy –  there is an sbt plugin, which gives you the same comfort and development speed as with Scala on the JVM. It can even run unit tests automatically with either Rhino, Node.js or PhantomJS, according to your needs.

Scala.js also has a growing ecosystem of libraries, which you can depend on through Maven dependencies (libraryDependencies in sbt). They cover UI frameworks, statically-typed client-server communication, reactive extensions, and so on. Several popular Scala community libraries such as Shapeless and Scalaz cross-compile with Scala.js.

Finally, we’re proud that Scala.js has a thriving community of nice and helpful people. Ask questions on StackOverflow, discuss on the mailing list, and discuss with us in the Gitter chat room.

Why Scala.js is awesome

We’ve asked developers who use Scala.js daily why they think Scala.js is awesome. Here is a distilled version of what they have answered, in decreasing order of how many people mentioned it. You can read the entire discussion on the mailing list.

  • 5 Share code between client and server
  • 4 Strong typing, including for JavaScript libraries
  • 4 Tooling: IDE support, sbt integration, dependency, unit testing, stack traces and source maps, cross-compiling projects
  • 4 Portability: bring Scala to environments powered by JavaScript, most importantly the browsers, but also others, such as the brand new React Native
  • 3 Integration with JavaScript
  • 2 Fast compilation cycle (wrt other compile-to-JS options such as GWT)
  • 2 Statically-checked client-server RPC with Autowire
  • 2 The Scala Standard library
  • 2 It’s not a toy
  • 2 Great community, welcoming to new users and helpful
  • 1 Very good documentation

Here are also a few selected quotes from the mailing list discussion.

It’s mostly about the strong typing for me. Nothing revolutionary about that idea, but it’s just as true on the client as on the server: having the compiler type-check your code makes it much quicker to get complex, sophisticated systems up and running.

Also, having the same language, end-to-end, is fabulous. […] With Scala.js, for the first time ever, I have a single solid, strongly-typed language that I can use throughout the system – from the fiddly details of the UI, through the API definitions and the front-end web server, to the Akka middleware and the database back end. That’s really kind of amazing. It is also why I personally think Scala.js is the killer app for Scala as a language. – Justin du Cœur

In a lot of ways, Scala.js frees your Scala code from the confines of the headless Linux server that it’s been running on for years. Scala might be a nice language, but you’ve never been able to use it to make anything cool that a non-backend-systems person would understand. […] With Scala.js, you can easily create small Scala applications and email the tiny 100kb executables (or just the link to them) to anyone, who can run them on any modern device, even smartphones. Made a cute game? A fun visualization? An animated sequence? Now you can show the world.

Scala’s no longer just for distributed systems people and type-theorists! – Li Haoyi

Before Scala.js I did investigate using Opa as another approach to get “End-to-End” type safety. The problem I had there was that to do JavaScript interop, I had to drop down from Opa into Ocaml and write out manual bindings to the JavaScript library I wanted to use. Scala.js’ approach is infinitely better. Despite how much better I think typed libraries are, that does not negate the fact that there are good and useful JS libraries out there, and the ability to “hack” it into Scala.js code effortlessly with js.Dynamic or add a typed facade if desired is fantastic. – Nick Childers

I have done some work with GWT before and compared to that the first thing you will notice is that Scala.js is FAST. It compiles 100 times faster, yet it still outputs JavaScript that is both faster and smaller. – Baldur Norddahl

Scala.js has very good tooling and very good documentation. If you already write JVM flavoured Scala you can be up and running in no time and write JS flavoured Scala. – Guillaume Belrose

[…] Scala.js has one of the smartest and most responsive communities I have ever seen. You, Li Haoyi, and many other posters here have contributed to making this platform welcoming to newcomers. The help I’ve received here has encouraged me to learn Scala proper, as well as many interesting functional programming concepts. – Travis Good

One of the biggest awesomeness of Scala.js is the core team’s steady hands. Right from the get go, Scala.js showed a mature engineering approach where each release made a meaningful difference to user projects, vetted release-to-release compatibility, communicated breaking changes well in advance, maintained useful associated libraries, and let pragmatism win over everything else. As a result, even though this is such a new project, it doesn’t feel risky to use it in real projects. – Ramnivas Laddad

Scala.js is simply the best option available on browsers today, if you’re looking for a language with a powerful yet flexible type system. – Xavier Cho

Why remove the experimental flag now?

Many Scala.js users would say that it has been production-ready for quite some time already. Possibly as early as 0.5.0, which was released in June 2014. So why do we choose to remove the experimental flag now? What has changed?

The big difference is several different aspects of stability:

  • The semantics of the language are settled. They may still evolve in a backward compatible way (defining previously undefined behaviors), but will otherwise not change anymore.
  • The standard library of Scala.js (the scala.scalajs.js package) will remain backward source and binary compatible.
  • The sbt builds will remain backward source compatible.

Of course, we must still be able to evolve the library and the builds, so things might become deprecated, and eventually removed, but will do so at a slower pace than before.

All things considered, this means that the code you write today, for Scala.js 0.6.0, will continue to work throughout 0.6.x and 1.x.y unchanged.

“So why isn’t it 1.0.0 already? It seems like these properties satisfy to the requirements of a 1.0.0 version. What are you hiding?”

While from all user-visible points of view Scala.js is stable, there remains just one quasi-implementation detail which might have to change in future versions – the format of the intermediate files of Scala.js, the .sjsir files. These files are essentially the Scala.js equivalent of .class files for the JVM. We’re not yet completely certain that we’re settled on their format, so we’d like to reserve the possibility of changing it in the coming months. Doing so means breaking binary compatibility (by definition), and therefore would require a change in major version number. So we’re not yet jumping to version 1.0.0 just yet – this is so that we may give ourselves one last chance to modify the Scala.js intermediate format before we make the leap to our first major version.

Though, rest assured! We’re confident that Scala.js is otherwise stable and ready for widespread adoption.

Getting started

There are three main ways to get started with Scala.js:

So go ahead! Use it, love it, and build the web applications of the future!

Recently...

date-icon Wednesday, January 14, 2015 announcement
We are very pleased to announce the release of Scala 2.11.5! Get started with the Hello Scala 2.11 template in Typesafe Activator Download a distribution...
date-icon Thursday, October 30, 2014 announcement
We are very pleased to announce the release of Scala 2.11.4! Get started with the Hello Scala 2.11 template in Typesafe Activator Download a distribution...
date-icon Monday, July 28, 2014 announcement
As with every living programming language, Scala will continue to evolve. This document describes where the core Scala team sees the language going in the...
date-icon
For more, visit our
News archive or Blog

Scala on Twitter


 
See more tweets, or
Follow Scala on Twitter
white Twitter logo