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

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 Friday, May 26, 2017

It has been a little bit more than two months since Scala Native 0.1 has been released. What’s new in Scala Native? What should you expect for future releases?

Scala Native 0.2

In April, Scala Native 0.2 was released. The main focus of this release was to increase the coverage of classes from the JDK, such that more programs can be ported to Scala Native without any further effort. What parts of Java do we now support in Scala Native? Lots! We’ve added support for IO and regular expressions, among others:

Improvements to the standard library

  • Support for file I/O APIs from java.io was added by @Duhemm from the Scala Center with help from @cedricviaccoz and @Korf74 in #574. Scala Native now supports enough to read and write files. Doing I/O with Scala Native feels just the same as in normal Scala or Java:

    import java.io.{DataInputStream, File, FileInputStream}
    val fis = new FileInputStream(new File("hello.txt"))
    val dis = new DataInputStream(fis)
    println(dis.readLine())
    
  • In #588, @MasseGuillaume from the Scala Center added support for regular expressions. This implementation relies on Google’s RE2 engine and uses a syntax slightly different from the JDK. Using regular expressions with Scala Native works similarly as it does on the JVM:

    import java.util.regex._
    val m = Pattern.compile("a+(b+)(a+)").matcher("aaabbba")
    assert(m.find())
    println(m.group(1)) // prints "bbb"
    println(m.group(2)) // prints "a"
    
  • @densh added initial support for Scala’s Futures in #618, using an implementation similar to that of Scala.js, where Futures will be completed after the main method is executed. Here’s an example using Scala’s Futures with Scala Native. Of course, the same code works as well on the JVM:

    import scala.concurrent.Future
    import scala.concurrent.ExecutionContext.Implicits.global
    
    object Test {
      def main(args: Array[String]): Unit = {
        println("Start")
        Future {
          println("Hello from the Future")
        }.foreach(_ => ())
        println("End")
      }
    }
    
  • Scala Native now supports pointer subtraction. This work has been contributed by @jonas in #624. Pointer subtraction is useful, for instance, to determine how many elements there are between two elements of the same array:

    val carr: Ptr[CChar] = toCString("abcdefg")
    val cptr: Ptr[CChar] = string.strchr(carr, 'd')
    println(cptr - carr) // prints '3'
    
  • @ekrich extended Scala Native’s implementation of String to support toUpperCase and toLowerCase in #573.
  • The implementation of java.lang.Character was extended to support Character.Subset and Character.UnicodeBlock by @densh in #651.
  • @asoltysik implemented support for system properties in #591.

    println(System.getProperty("java.version"))   // prints '1.8'
    println(System.getProperty("file.separator")) // '\' on Windows,
                                                  // '/' elsewhere
    
  • Scala Native can now read environment variables using System.getEnv, thanks to @jonas’ efforts in #606.
  • stdin and stdout can reliably be read from and written to, thanks to @fduraffourg and @densh in #622 and #659.

Bugfixes

  • A bugfix has been contributed by @jonas to String.replace, fixing one broken benchmark at the same time. His work can be found in #616.
  • System.nanoTime was fixed by @brad-rathke in #549.
  • @xuwei-k fixed nativeAvailableDependencies which didn’t work in the test configuration in #565.

Improvements to the tooling and integration

  • @MasseGuillaume and @densh worked on refactoring Scala Native’s sbt plugin to make it more idiomatic in #568 and #630.
  • Follow up fixes were contributed by @jonas in #639 and #653. They improve how sbt determines the target architecture to compile to.

Preparing for a better garbage collector

In this release, @LukasKellenberger introduced in #539 a new setting in the sbt plugin that lets users select what implementation of the garbage collector should be used. Currently, it lets you select Boehm GC, or disable the garbage collector altogether.

This work was done in preparation for the improved GC that will be shipped with Scala Native 0.3!

A community effort

As shown, many of the improvements that were brought by Scala Native 0.2 have been contributed by members of the vibrant community that is developing itself around Scala Native. In total, to get to Scala Native 0.2, there have been 61 commits merged, 11,344 lines added and 1,954 lines deleted by 17 people: Denys Shabalin, Jonas Fonseca, Guillaume Massé, Martin Duhem, Lukas Kellenberger, Andrzej Sołtysik, Eric K Richardson, Remi Coudert, Florian Duraffour, Brad Rathke, Richard Whaling, Ruben Berenguel M, Sam Halliday, Shunsuke Otani, Cedric Viaccoz, Kenji Yoshida, Ignat Loskutov.

The combination of these improvements was enough to get a prototype of scalafmt running on Scala Native by @olafurpg, showing a blazing fast startup time!

What to expect for Scala Native 0.3?

The plans for the next release of Scala Native include a new garbage collector, a better integration with sbt and more additions to the standard library.

Improved garbage collector

The first releases of Scala Native use Boehm GC. A new and improved garbage collector has been under development by @LukasKellenberger and will be presented at Scala Days during Denys’ talk. Stay tuned for more more details to come soon!

The pull request introducing the new garbage collector can be found in #726.

Running tests from sbt

Currently, testing frameworks such as utest or scalacheck cannot be used with Scala Native. An effort to enable support for sbt-compatible testing frameworks has been undertaken by @Duhemm from the Scala Center and is expected to land in Scala Native’s third release.

Support for java.nio, java.util.{jar, zip}

The existing I/O capabilities of Scala Native have been extended in this release by adding support for the classes defined in the packages java.nio, java.util.jar and java.util.zip.

Smaller binaries

In #686, @densh started work to reduce the size of the binaries compiled by Scala Native, using a technique called selector-based row displacement.

These improvements make the dispatch table up to 10 times smaller, on some codebases in the wild.

0.4 and beyond

Some features are already in the works for Scala Native 0.4.

Windows support

@muxanick has been working on a port of Scala Native to Windows. The advancement of his work can be consulted in #691.

Automatic binding generation

A prototype of automatic binding generation is in development by @jonas. The goal is to be able to generate automatically bindings for C libraries. For instance, given the following C header test.h:

enum color {
  RED = 1,
  GREEN,
  BLUE = 100
};
typedef int SomeInt;
char *strchr(const char *s, int c);

We want to generate the following definitions:

@extern
object Test {
  object color {
    val RED = 1
    val GREEN = 2
    val BLUE = 100
  }
  type SomeInt = CInt
  def strchr(s: CString, c: CInt): CString = extern
}

Ultimately, this tool will make it much easier to providing bindings for C’s stdlib and external libraries.

Recently...

date-icon Friday, May 19, 2017 blog
The Scala Center team is extremely happy to announce that Scastie is out of beta! That means anyone can use Scala in the browser over...
date-icon Tuesday, April 18, 2017 announcement
We are happy to announce three new Scala releases: 2.11.11 concludes the 2.11 series, 2.12.2 brings bug fixes and small improvements, and 2.13.0-M1 sets the...
date-icon Saturday, April 01, 2017 blog
Introducing Skala: A New Vision for Dotty We are very proud today to be able to reveal that Dotty, sometimes referred to as “Scala 3”,...
date-icon
For more, visit our
News archive or Blog

Scala on Twitter