Object-Oriented Meets Functional

Scala is a statically typed programming language
that lets you enjoy the best of both worlds.

Develop fast, expressive applications and libraries
with broad editor support and great tooling.

Run them on the JVM, in the browser, on Android
– and soon – compiled to native code.

Learn More
Download API Docs    
Spiral
Scala
2.11.8

Scala in a Nutshell

 click the boxes below to see Scala in action! 

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.

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

Extensible

Conext Bounds

Implicit Classes

X
// Old legacy library
class Person(val first: String, last: String, val born: String)
Y
// Interface of new API
trait Human {
  def firstName: String
  def lastName:  String
  def fullName = s"$firstName $lastName"
  def dateOfBirth: java.time.LocalDate
  def age: java.time.Period = dateOfBirth until java.time.LocalDate.now
}
Z
// Bridge the gap
implicit class PersonAsHuman(person: Person) extends Human {
  def firstName = person.first
  def lastName  = person.last
  val dateOfBirth = java.time.LocalDate.parse(person.born)
}
Z
// Usage
val joe = new Person("Joe", "Smith", 42) // from old library
joe.first // old API works
joe.firstName // new API
joe.fullName // new API we got for free

// API from new library
def isAdult(human: Human): Boolean = ???
// pass joe, without requring explicit conversion
isAdult(joe)
hasBirthDay

Editors

ScalaIDE – The Scala Plugin for Eclipse

ScalaIDE is a plugin for the popular Eclipse IDE. You can download a bundled version which contains both the Scala plugin and the Eclipse IDE: Download ScalaIDE Bundle

The bundle contains the lastest release version of the Scala IDE for Eclipse and it comes pre-configured for optimal performance. No need to configure update sites, and Check for updates will keep your development environment up to date.

Whether you are a seasoned Scala developer, or just picking up the language, this is the fastest way to get productive.

Alternatively, you can add the ScalaIDE to your existing Eclipse installation:Add ScalaIDE Update Site

Scala Plugin for IntelliJ

JetBrains provides a Scala plugin which works in the community as well as the commercial version of their IntelliJ IDE.

It turns IntelliJ into a fully featured Scala IDE offering syntax highlighting, warning/error markers, auto-completion, refactorings, inspections and intentions.

Just place a *.scala file in your project and IntelliJ will offer to download and install the IntelliJ Scala plugin: Scala Plugin for IntelliJ

Scala for Emacs

Using the world's best editor? Scala got you covered!

Scala for Emacs

Scala for Sublime

Here is a pictured walkthrough to help you getting started:Install Scala for Sublime

Scala for Atom

Use Scala with GitHub's Atom editor!Install Scala for Atom

Scala for Vim

Vim is an extremely configurable/extensible text editor.

Scala supports both Vim and Neovim.

Scala for Vim

Tooling

– The Scala Build Tool

Get SBT

What's New

blog
date icon Monday, August 15, 2016

On August 10, the Scala Improvement Process (SIP) Committee held their monthly meeting to discuss and give feedback on four proposals, both new and old. We’re happy that these discussions sparked so much interest and participation in the community. It’s comforting to see the new SIP process becoming fruitful!

Of the four discussed proposals, two were unanimously rejected. The other two progressed and will have a follow-up iteration.

The rejected proposals were:

  • SIP-12: Uncluttering Scala’s syntax for control structures. Originally proposed in 2011. The proposal suggested syntax changes in if’s, for and while loops, moving Scala’s syntax away from Java and C-like languages. Whereas such changes may be arguably more beautiful, the Committee agreed that would give more problems than benefits. Seth Tisue, the appointed reviewer, fully explains the Committee’s reaction here.
  • SIP-16: Self-cleaning macros. Originally proposed in 2012. Macros add a whole new dimension to the Scala language. Their experimental implementation was adopted by a lot of Scala libraries and were immensely useful for the creation and evolution of first-class Scala tools. As described by his creator and reviewer, Eugene Burmako, they turned out to be a good experiment, but one that could be improved if major downsides in the design were addressed. With the intention of letting scala.meta eventually replace the old macros, he proposed rejecting SIP-16 to revisit its basic foundations and create a new proposal that would considerably enhance the metaprogramming experience in Scala. In the meantime, the experimental implementation will remain in place. If you’re interested in Eugene’s explanation, follow this.

The two proposals that made it to the next iteration are SIP-23: Literal-based singleton types (reviewer: Adriaan Moors) and SIP-27: Trailing Commas (reviewer: Eugene Burmako). The reviewers and committee members provided more feedback to iterate on. Both proposals already have provisional implementations and will continue to be discussed for inclusion in the language.

Overall, we’re happy to report these results and see Scala continue to move forward! We’re excited to see the Scala community speaking up and collaborating with the process—your vibrant responses will greatly enrich our future deliberations.

Next month, we’ll discuss five more proposals, including SIP-21: Spores and SIP-24: Repeated by-name parameters. We hope to finish off the list of old proposals in the queue and focus ourselves on the most recent proposals and the ones that are to come!

Did you know that each month, we conduct these SIP meetings on-air? You can tune in and ask questions to the SIP committee, and have them answered live. Videos of the meetings are then archived on YouTube. Check the minutes of this meeting in the SIP website.

Recently...

date-icon
date-icon Tuesday, August 09, 2016 blog
Today, the Scala Center team is very proud to announce that The Scala Package Index, or Scaladex for short, has reached beta v1! This means...
date-icon Wednesday, July 20, 2016 blog
Last week, the Scala Center ran its first SIP meeting under the newly reformed SIP process, and we’re happy to report that several SIPs saw...
date-icon Tuesday, July 12, 2016 blog
This past May, we held our first advisory board meeting, to discuss some of the areas that the newly-formed Scala Center should focus on. One...
More News & Announcements

Upcoming Events

See more events or add one to our feed