Packages

  • package root

    This is the documentation for the Scala standard library.

    This is the documentation for the Scala standard library.

    Package structure

    The scala package contains core types like Int, Float, Array or Option which are accessible in all Scala compilation units without explicit qualification or imports.

    Notable packages include:

    Other packages exist. See the complete list on the right.

    Additional parts of the standard library are shipped as separate libraries. These include:

    • scala.reflect - Scala's reflection API (scala-reflect.jar)
    • scala.xml - XML parsing, manipulation, and serialization (scala-xml.jar)
    • scala.swing - A convenient wrapper around Java's GUI framework called Swing (scala-swing.jar)
    • scala.util.parsing - Parser combinators (scala-parser-combinators.jar)

    Automatic imports

    Identifiers in the scala package and the scala.Predef object are always in scope by default.

    Some of these identifiers are type aliases provided as shortcuts to commonly used classes. For example, List is an alias for scala.collection.immutable.List.

    Other aliases refer to classes provided by the underlying platform. For example, on the JVM, String is an alias for java.lang.String.

    Definition Classes
    root
  • package scala

    Core Scala types.

    Core Scala types. They are always available without an explicit import.

    Definition Classes
    root
  • package annotation
    Definition Classes
    scala
  • package beans
    Definition Classes
    scala
  • package collection

    Contains the base traits and objects needed to use and extend Scala's collection library.

    Contains the base traits and objects needed to use and extend Scala's collection library.

    Guide

    A detailed guide for using the collections library is available at http://docs.scala-lang.org/overviews/collections/introduction.html. Developers looking to extend the collections library can find a description of its architecture at http://docs.scala-lang.org/overviews/core/architecture-of-scala-collections.html.

    Using Collections

    It is convenient to treat all collections as either a scala.collection.Traversable or scala.collection.Iterable, as these traits define the vast majority of operations on a collection.

    Collections can, of course, be treated as specifically as needed, and the library is designed to ensure that the methods that transform collections will return a collection of the same type:

    scala> val array = Array(1,2,3,4,5,6)
    array: Array[Int] = Array(1, 2, 3, 4, 5, 6)
    
    scala> array map { _.toString }
    res0: Array[String] = Array(1, 2, 3, 4, 5, 6)
    
    scala> val list = List(1,2,3,4,5,6)
    list: List[Int] = List(1, 2, 3, 4, 5, 6)
    
    scala> list map { _.toString }
    res1: List[String] = List(1, 2, 3, 4, 5, 6)

    Creating Collections

    The most common way to create a collection is to use its companion object as a factory. The three most commonly used collections are scala.collection.Seq, scala.collection.immutable.Set, and scala.collection.immutable.Map. They can be used directly as shown below since their companion objects are all available as type aliases in either the scala package or in scala.Predef. New collections are created like this:

    scala> val seq = Seq(1,2,3,4,1)
    seq: Seq[Int] = List(1, 2, 3, 4, 1)
    
    scala> val set = Set(1,2,3,4,1)
    set: scala.collection.immutable.Set[Int] = Set(1, 2, 3, 4)
    
    scala> val map = Map(1 -> "one", 2 -> "two", 3 -> "three", 2 -> "too")
    map: scala.collection.immutable.Map[Int,String] = Map(1 -> one, 2 -> too, 3 -> three)

    It is also typical to prefer the scala.collection.immutable collections over those in scala.collection.mutable; the types aliased in the scala.Predef object are the immutable versions.

    Also note that the collections library was carefully designed to include several implementations of each of the three basic collection types. These implementations have specific performance characteristics which are described in the guide.

    The concrete parallel collections also have specific performance characteristics which are described in the parallel collections guide

    Converting to and from Java Collections

    The scala.collection.JavaConverters object provides a collection of decorators that allow converting between Scala and Java collections using asScala and asJava methods.

    Definition Classes
    scala
  • package compat
    Definition Classes
    scala
  • package concurrent

    This package object contains primitives for concurrent and parallel programming.

    This package object contains primitives for concurrent and parallel programming.

    Guide

    A more detailed guide to Futures and Promises, including discussion and examples can be found at http://docs.scala-lang.org/overviews/core/futures.html.

    Common Imports

    When working with Futures, you will often find that importing the whole concurrent package is convenient:

    import scala.concurrent._

    When using things like Futures, it is often required to have an implicit ExecutionContext in scope. The general advice for these implicits are as follows.

    If the code in question is a class or method definition, and no ExecutionContext is available, request one from the caller by adding an implicit parameter list:

    def myMethod(myParam: MyType)(implicit ec: ExecutionContext) = …
    //Or
    class MyClass(myParam: MyType)(implicit ec: ExecutionContext) { … }

    This allows the caller of the method, or creator of the instance of the class, to decide which ExecutionContext should be used.

    For typical REPL usage and experimentation, importing the global ExecutionContext is often desired.

    import scala.concurrent.ExcutionContext.Implicits.global

    Specifying Durations

    Operations often require a duration to be specified. A duration DSL is available to make defining these easier:

    import scala.concurrent.duration._
    val d: Duration = 10.seconds

    Using Futures For Non-blocking Computation

    Basic use of futures is easy with the factory method on Future, which executes a provided function asynchronously, handing you back a future result of that function without blocking the current thread. In order to create the Future you will need either an implicit or explicit ExecutionContext to be provided:

    import scala.concurrent._
    import ExecutionContext.Implicits.global  // implicit execution context
    
    val firstZebra: Future[Int] = Future {
      val source = scala.io.Source.fromFile("/etc/dictionaries-common/words")
      source.toSeq.indexOfSlice("zebra")
    }

    Avoid Blocking

    Although blocking is possible in order to await results (with a mandatory timeout duration):

    import scala.concurrent.duration._
    Await.result(firstZebra, 10.seconds)

    and although this is sometimes necessary to do, in particular for testing purposes, blocking in general is discouraged when working with Futures and concurrency in order to avoid potential deadlocks and improve performance. Instead, use callbacks or combinators to remain in the future domain:

    val animalRange: Future[Int] = for {
      aardvark <- firstAardvark
      zebra <- firstZebra
    } yield zebra - aardvark
    
    animalRange.onSuccess {
      case x if x > 500000 => println("It's a long way from Aardvark to Zebra")
    }
    Definition Classes
    scala
  • package duration
  • package forkjoin
  • Await
  • Awaitable
  • BlockContext
  • CanAwait
  • Channel
  • DelayedLazyVal
  • ExecutionContext
  • ExecutionContextExecutor
  • ExecutionContextExecutorService
  • Future
  • JavaConversions
  • Lock
  • OnCompleteRunnable
  • Promise
  • SyncChannel
  • SyncVar
  • package io
    Definition Classes
    scala
  • package math

    The package object scala.math contains methods for performing basic numeric operations such as elementary exponential, logarithmic, root and trigonometric functions.

    The package object scala.math contains methods for performing basic numeric operations such as elementary exponential, logarithmic, root and trigonometric functions.

    All methods forward to java.lang.Math unless otherwise noted.

    Definition Classes
    scala
    See also

    java.lang.Math

  • package ref
    Definition Classes
    scala
  • package reflect
    Definition Classes
    scala
  • package runtime
    Definition Classes
    scala
  • package sys

    The package object scala.sys contains methods for reading and altering core aspects of the virtual machine as well as the world outside of it.

    The package object scala.sys contains methods for reading and altering core aspects of the virtual machine as well as the world outside of it.

    Definition Classes
    scala
    Version

    2.9

    Since

    2.9

  • package text
    Definition Classes
    scala
  • package util
    Definition Classes
    scala
p

scala

concurrent

package concurrent

This package object contains primitives for concurrent and parallel programming.

Guide

A more detailed guide to Futures and Promises, including discussion and examples can be found at http://docs.scala-lang.org/overviews/core/futures.html.

Common Imports

When working with Futures, you will often find that importing the whole concurrent package is convenient:

import scala.concurrent._

When using things like Futures, it is often required to have an implicit ExecutionContext in scope. The general advice for these implicits are as follows.

If the code in question is a class or method definition, and no ExecutionContext is available, request one from the caller by adding an implicit parameter list:

def myMethod(myParam: MyType)(implicit ec: ExecutionContext) = …
//Or
class MyClass(myParam: MyType)(implicit ec: ExecutionContext) { … }

This allows the caller of the method, or creator of the instance of the class, to decide which ExecutionContext should be used.

For typical REPL usage and experimentation, importing the global ExecutionContext is often desired.

import scala.concurrent.ExcutionContext.Implicits.global

Specifying Durations

Operations often require a duration to be specified. A duration DSL is available to make defining these easier:

import scala.concurrent.duration._
val d: Duration = 10.seconds

Using Futures For Non-blocking Computation

Basic use of futures is easy with the factory method on Future, which executes a provided function asynchronously, handing you back a future result of that function without blocking the current thread. In order to create the Future you will need either an implicit or explicit ExecutionContext to be provided:

import scala.concurrent._
import ExecutionContext.Implicits.global  // implicit execution context

val firstZebra: Future[Int] = Future {
  val source = scala.io.Source.fromFile("/etc/dictionaries-common/words")
  source.toSeq.indexOfSlice("zebra")
}

Avoid Blocking

Although blocking is possible in order to await results (with a mandatory timeout duration):

import scala.concurrent.duration._
Await.result(firstZebra, 10.seconds)

and although this is sometimes necessary to do, in particular for testing purposes, blocking in general is discouraged when working with Futures and concurrency in order to avoid potential deadlocks and improve performance. Instead, use callbacks or combinators to remain in the future domain:

val animalRange: Future[Int] = for {
  aardvark <- firstAardvark
  zebra <- firstZebra
} yield zebra - aardvark

animalRange.onSuccess {
  case x if x > 500000 => println("It's a long way from Aardvark to Zebra")
}
Source
package.scala
Linear Supertypes
Ordering
  1. Alphabetic
  2. By Inheritance
Inherited
  1. concurrent
  2. AnyRef
  3. Any
  1. Hide All
  2. Show All
Visibility
  1. Public
  2. All

Type Members

  1. trait Awaitable [+T] extends AnyRef

    An object that may eventually be completed with a result value of type T which may be awaited using blocking methods.

    An object that may eventually be completed with a result value of type T which may be awaited using blocking methods.

    The Await object provides methods that allow accessing the result of an Awaitable by blocking the current thread until the Awaitable has been completed or a timeout has occurred.

  2. trait BlockContext extends AnyRef

    A context to be notified by scala.concurrent.blocking when a thread is about to block.

    A context to be notified by scala.concurrent.blocking when a thread is about to block. In effect this trait provides the implementation for scala.concurrent.Await. scala.concurrent.Await.result() and scala.concurrent.Await.ready() locates an instance of BlockContext by first looking for one provided through BlockContext.withBlockContext() and failing that, checking whether Thread.currentThread is an instance of BlockContext. So a thread pool can have its java.lang.Thread instances implement BlockContext. There's a default BlockContext used if the thread doesn't implement BlockContext.

    Typically, you'll want to chain to the previous BlockContext, like this:

    val oldContext = BlockContext.current
    val myContext = new BlockContext {
      override def blockOn[T](thunk: =>T)(implicit permission: CanAwait): T = {
        // you'd have code here doing whatever you need to do
        // when the thread is about to block.
        // Then you'd chain to the previous context:
        oldContext.blockOn(thunk)
      }
    }
    BlockContext.withBlockContext(myContext) {
      // then this block runs with myContext as the handler
      // for scala.concurrent.blocking
    }
  3. sealed trait CanAwait extends AnyRef

    This marker trait is used by Await to ensure that Awaitable.ready and Awaitable.result are not directly called by user code.

    This marker trait is used by Await to ensure that Awaitable.ready and Awaitable.result are not directly called by user code. An implicit instance of this trait is only available when user code is currently calling the methods on Await.

    Annotations
    @implicitNotFound( msg = ... )
  4. type CancellationException = java.util.concurrent.CancellationException
  5. class Channel [A] extends AnyRef

    This class provides a simple FIFO queue of data objects, which are read by one or more reader threads.

    This class provides a simple FIFO queue of data objects, which are read by one or more reader threads.

    A

    type of data exchanged

    Version

    1.0, 10/03/2003

  6. class DelayedLazyVal [T] extends AnyRef

    A DelayedLazyVal is a wrapper for lengthy computations which have a valid partially computed result.

    A DelayedLazyVal is a wrapper for lengthy computations which have a valid partially computed result.

    The first argument is a function for obtaining the result at any given point in time, and the second is the lengthy computation. Once the computation is complete, the apply method will stop recalculating it and return a fixed value from that point forward.

    Version

    2.8

  7. trait ExecutionContext extends AnyRef

    An ExecutionContext can execute program logic asynchronously, typically but not necessarily on a thread pool.

    An ExecutionContext can execute program logic asynchronously, typically but not necessarily on a thread pool.

    A general purpose ExecutionContext must be asynchronous in executing any Runnable that is passed into its execute-method. A special purpose ExecutionContext may be synchronous but must only be passed to code that is explicitly safe to be run using a synchronously executing ExecutionContext.

    APIs such as Future.onComplete require you to provide a callback and an implicit ExecutionContext. The implicit ExecutionContext will be used to execute the callback.

    While it is possible to simply import scala.concurrent.ExecutionContext.Implicits.global to obtain an implicit ExecutionContext, application developers should carefully consider where they want to set execution policy; ideally, one place per application—or per logically related section of code— will make a decision about which ExecutionContext to use. That is, you will mostly want to avoid hardcoding, especially via an import, scala.concurrent.ExecutionContext.Implicits.global. The recommended approach is to add (implicit ec: ExecutionContext) to methods, or class constructor parameters, which need an ExecutionContext.

    Then locally import a specific ExecutionContext in one place for the entire application or module, passing it implicitly to individual methods. Alternatively define a local implicit val with the required ExecutionContext.

    A custom ExecutionContext may be appropriate to execute code which blocks on IO or performs long-running computations. ExecutionContext.fromExecutorService and ExecutionContext.fromExecutor are good ways to create a custom ExecutionContext.

    The intent of ExecutionContext is to lexically scope code execution. That is, each method, class, file, package, or application determines how to run its own code. This avoids issues such as running application callbacks on a thread pool belonging to a networking library. The size of a networking library's thread pool can be safely configured, knowing that only that library's network operations will be affected. Application callback execution can be configured separately.

    Annotations
    @implicitNotFound( msg = ... )
  8. trait ExecutionContextExecutor extends ExecutionContext with Executor

    An ExecutionContext that is also a Java Executor.

  9. trait ExecutionContextExecutorService extends ExecutionContextExecutor with ExecutorService

    An ExecutionContext that is also a Java ExecutorService.

  10. type ExecutionException = java.util.concurrent.ExecutionException
  11. trait Future [+T] extends Awaitable[T]

    A Future represents a value which may or may not *currently* be available, but will be available at some point, or an exception if that value could not be made available.

    A Future represents a value which may or may not *currently* be available, but will be available at some point, or an exception if that value could not be made available.

    Asynchronous computations that yield futures are created with the Future.apply call and are computed using a supplied ExecutionContext, which can be backed by a Thread pool.

    import ExecutionContext.Implicits.global
    val s = "Hello"
    val f: Future[String] = Future {
      s + " future!"
    }
    f foreach {
      msg => println(msg)
    }
    See also

    Futures and Promises

  12. trait OnCompleteRunnable extends AnyRef

    A marker indicating that a java.lang.Runnable provided to scala.concurrent.ExecutionContext wraps a callback provided to Future.onComplete.

    A marker indicating that a java.lang.Runnable provided to scala.concurrent.ExecutionContext wraps a callback provided to Future.onComplete. All callbacks provided to a Future end up going through onComplete, so this allows an ExecutionContext to special-case callbacks that were executed by Future if desired.

  13. trait Promise [T] extends AnyRef

    Promise is an object which can be completed with a value or failed with an exception.

  14. class SyncChannel [A] extends AnyRef

    A SyncChannel allows one to exchange data synchronously between a reader and a writer thread.

    A SyncChannel allows one to exchange data synchronously between a reader and a writer thread. The writer thread is blocked until the data to be written has been read by a corresponding reader thread.

    Version

    2.0, 04/17/2008

  15. class SyncVar [A] extends AnyRef

    A class to provide safe concurrent access to a mutable cell.

    A class to provide safe concurrent access to a mutable cell. All methods are synchronized.

    A

    type of the contained value

    Version

    1.0, 10/03/2003

  16. type TimeoutException = java.util.concurrent.TimeoutException
  17. class Lock extends AnyRef

    This class ...

    This class ...

    Annotations
    @deprecated
    Deprecated

    (Since version 2.11.2) use java.util.concurrent.locks.Lock

    Version

    1.0, 10/03/2003

Value Members

  1. def blocking[T](body: ⇒ T): T

    Used to designate a piece of code which potentially blocks, allowing the current BlockContext to adjust the runtime's behavior.

    Used to designate a piece of code which potentially blocks, allowing the current BlockContext to adjust the runtime's behavior. Properly marking blocking code may improve performance or avoid deadlocks.

    Blocking on an Awaitable should be done using Await.result instead of blocking.

    body

    A piece of code which contains potentially blocking or long running calls.

    Annotations
    @throws( clazz = classOf[Exception] )
    Exceptions thrown

    CancellationException if the computation was cancelled

    InterruptedException in the case that a wait within the blocking body was interrupted

  2. object Await

    Await is what is used to ensure proper handling of blocking for Awaitable instances.

    Await is what is used to ensure proper handling of blocking for Awaitable instances.

    While occasionally useful, e.g. for testing, it is recommended that you avoid Await whenever possible— instead favoring combinators and/or callbacks. Await's result and ready methods will block the calling thread's execution until they return, which will cause performance degradation, and possibly, deadlock issues.

  3. object BlockContext
  4. object ExecutionContext

    Contains factory methods for creating execution contexts.

  5. object Future

    Future companion object.

  6. object JavaConversions

    The JavaConversions object provides implicit conversions supporting interoperability between Scala and Java concurrency classes.

  7. object Promise

Deprecated Value Members

  1. def future[T](body: ⇒ T)(implicit executor: ExecutionContext): Future[T]

    Starts an asynchronous computation and returns a Future object with the result of that computation.

    Starts an asynchronous computation and returns a Future object with the result of that computation.

    The result becomes available once the asynchronous computation is completed.

    T

    the type of the result

    body

    the asynchronous computation

    executor

    the execution context on which the future is run

    returns

    the Future holding the result of the computation

    Annotations
    @deprecated
    Deprecated

    (Since version 2.11.0) use Future { ... } instead

  2. def promise[T](): Promise[T]

    Creates a promise object which can be completed with a value or an exception.

    Creates a promise object which can be completed with a value or an exception.

    T

    the type of the value in the promise

    returns

    the newly created Promise object

    Annotations
    @deprecated
    Deprecated

    (Since version 2.11.0) use Promise[T]() instead

Inherited from AnyRef

Inherited from Any

Ungrouped