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 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
  • package control
  • package hashing
  • package matching
  • DynamicVariable
  • Either
  • Failure
  • Left
  • MurmurHash
  • Properties
  • Random
  • Right
  • Sorting
  • Success
  • Try
p

scala

util

package util

Ordering
  1. Alphabetic
Visibility
  1. Public
  2. All

Type Members

  1. class DynamicVariable [T] extends AnyRef

    DynamicVariables provide a binding mechanism where the current value is found through dynamic scope, but where access to the variable itself is resolved through static scope.

    DynamicVariables provide a binding mechanism where the current value is found through dynamic scope, but where access to the variable itself is resolved through static scope.

    The current value can be retrieved with the value method. New values should be pushed using the withValue method. Values pushed via withValue only stay valid while the withValue's second argument, a parameterless closure, executes. When the second argument finishes, the variable reverts to the previous value.

    someDynamicVariable.withValue(newValue) {
      // ... code called in here that calls value ...
      // ... will be given back the newValue ...
    }

    Each thread gets its own stack of bindings. When a new thread is created, the DynamicVariable gets a copy of the stack of bindings from the parent thread, and from then on the bindings for the new thread are independent of those for the original thread.

    Version

    1.1, 2007-5-21

  2. sealed abstract class Either [+A, +B] extends Product with Serializable

    Represents a value of one of two possible types (a disjoint union.) An instance of Either is an instance of either scala.util.Left or scala.util.Right.

    Represents a value of one of two possible types (a disjoint union.) An instance of Either is an instance of either scala.util.Left or scala.util.Right.

    A common use of Either is as an alternative to scala.Option for dealing with possibly missing values. In this usage, scala.None is replaced with a scala.util.Left which can contain useful information. scala.util.Right takes the place of scala.Some. Convention dictates that Left is used for failure and Right is used for success.

    For example, you could use Either[String, Int] to indicate whether a received input is a String or an Int.

    import scala.io.StdIn._
    val in = readLine("Type Either a string or an Int: ")
    val result: Either[String,Int] =
      try Right(in.toInt)
      catch {
        case e: NumberFormatException => Left(in)
      }
    
    result match {
      case Right(x) => s"You passed me the Int: $x, which I will increment. $x + 1 = ${x+1}"
      case Left(x)  => s"You passed me the String: $x"
    }

    Either is right-biased, which means that Right is assumed to be the default case to operate on. If it is Left, operations like map and flatMap return the Left value unchanged:

    def doubled(i: Int) = i * 2
    Right(42).map(doubled) // Right(84)
    Left(42).map(doubled)  // Left(42)

    Since Either defines the methods map and flatMap, it can also be used in for comprehensions:

    val right1 = Right(1)   : Right[Double, Int]
    val right2 = Right(2)
    val right3 = Right(3)
    val left23 = Left(23.0) : Left[Double, Int]
    val left42 = Left(42.0)
    
    for {
      x <- right1
      y <- right2
      z <- right3
    } yield x + y + z // Right(6)
    
    for {
      x <- right1
      y <- right2
      z <- left23
    } yield x + y + z // Left(23.0)
    
    for {
      x <- right1
      y <- left23
      z <- right2
    } yield x + y + z // Left(23.0)
    
    // Guard expressions are not supported:
    for {
      i <- right1
      if i > 0
    } yield i
    // error: value withFilter is not a member of Right[Double,Int]
    
    // Similarly, refutable patterns are not supported:
    for (x: Int <- right1) yield x
    // error: value withFilter is not a member of Right[Double,Int]

    Since for comprehensions use map and flatMap, the types of function parameters used in the expression must be inferred. These types are constrained by the Either values. In particular, because of right-biasing, Left values may require an explicit type argument for type parameter B, the right value. Otherwise, it might be inferred as Nothing.

    for {
      x <- left23
      y <- right1
      z <- left42  // type at this position: Either[Double, Nothing]
    } yield x + y + z
    //            ^
    // error: ambiguous reference to overloaded definition,
    // both method + in class Int of type (x: Char)Int
    // and  method + in class Int of type (x: Byte)Int
    // match argument types (Nothing)
    
    for (x <- right2 ; y <- left23) yield x + y  // Left(23.0)
    for (x <- right2 ; y <- left42) yield x + y  // error
    
    for {
      x <- right1
      y <- left42  // type at this position: Either[Double, Nothing]
      z <- left23
    } yield x + y + z
    // Left(42.0), but unexpectedly a `Either[Double,String]`
    Version

    2.0, 2016-07-15

    Since

    2.7

  3. final case class Failure [+T](exception: Throwable) extends Try[T] with Product with Serializable
  4. final case class Left [+A, +B](value: A) extends Either[A, B] with Product with Serializable

    The left side of the disjoint union, as opposed to the scala.util.Right side.

    The left side of the disjoint union, as opposed to the scala.util.Right side.

    Version

    1.0, 11/10/2008

  5. class Random extends Serializable

  6. final case class Right [+A, +B](value: B) extends Either[A, B] with Product with Serializable

    The right side of the disjoint union, as opposed to the scala.util.Left side.

    The right side of the disjoint union, as opposed to the scala.util.Left side.

    Version

    1.0, 11/10/2008

  7. final case class Success [+T](value: T) extends Try[T] with Product with Serializable
  8. sealed abstract class Try [+T] extends Product with Serializable

    The Try type represents a computation that may either result in an exception, or return a successfully computed value.

    The Try type represents a computation that may either result in an exception, or return a successfully computed value. It's similar to, but semantically different from the scala.util.Either type.

    Instances of Try[T], are either an instance of scala.util.Success[T] or scala.util.Failure[T].

    For example, Try can be used to perform division on a user-defined input, without the need to do explicit exception-handling in all of the places that an exception might occur.

    Example:

    import scala.io.StdIn
    import scala.util.{Try, Success, Failure}
    
    def divide: Try[Int] = {
      val dividend = Try(StdIn.readLine("Enter an Int that you'd like to divide:\n").toInt)
      val divisor = Try(StdIn.readLine("Enter an Int that you'd like to divide by:\n").toInt)
      val problem = dividend.flatMap(x => divisor.map(y => x/y))
      problem match {
        case Success(v) =>
          println("Result of " + dividend.get + "/"+ divisor.get +" is: " + v)
          Success(v)
        case Failure(e) =>
          println("You must've divided by zero or entered something that's not an Int. Try again!")
          println("Info from the exception: " + e.getMessage)
          divide
      }
    }

    An important property of Try shown in the above example is its ability to pipeline, or chain, operations, catching exceptions along the way. The flatMap and map combinators in the above example each essentially pass off either their successfully completed value, wrapped in the Success type for it to be further operated upon by the next combinator in the chain, or the exception wrapped in the Failure type usually to be simply passed on down the chain. Combinators such as recover and recoverWith are designed to provide some type of default behavior in the case of failure.

    Note: only non-fatal exceptions are caught by the combinators on Try (see scala.util.control.NonFatal). Serious system errors, on the other hand, will be thrown.

    Note:: all Try combinators will catch exceptions and return failure unless otherwise specified in the documentation.

    Try comes to the Scala standard library after years of use as an integral part of Twitter's stack.

    Since

    2.10

  9. class MurmurHash [T] extends (T) ⇒ Unit

    A class designed to generate well-distributed non-cryptographic hashes.

    A class designed to generate well-distributed non-cryptographic hashes. It is designed to be passed to a collection's foreach method, or can take individual hash values with append. Its own hash code is set equal to the hash code of whatever it is hashing.

    Annotations
    @deprecated
    Deprecated

    (Since version 2.10.0) use the object MurmurHash3 instead

Value Members

  1. object Either extends Serializable
  2. object Properties extends PropertiesTrait

    Loads library.properties from the jar.

  3. object Random extends Random

    The object Random offers a default implementation of scala.util.Random and random-related convenience methods.

    The object Random offers a default implementation of scala.util.Random and random-related convenience methods.

    Since

    2.8

  4. object Sorting

    The Sorting object provides convenience wrappers for java.util.Arrays.sort.

    The Sorting object provides convenience wrappers for java.util.Arrays.sort. Methods that defer to java.util.Arrays.sort say that they do or under what conditions that they do.

    Sorting also implements a general-purpose quicksort and stable (merge) sort for those cases where java.util.Arrays.sort could only be used at the cost of a large memory penalty. If performance rather than memory usage is the primary concern, one may wish to find alternate strategies to use java.util.Arrays.sort directly e.g. by boxing primitives to use a custom ordering on them.

    Sorting provides methods where you can provide a comparison function, or can request a sort of items that are scala.math.Ordered or that otherwise have an implicit or explicit scala.math.Ordering.

    Note also that high-performance non-default sorts for numeric types are not provided. If this is required, it is advisable to investigate other libraries that cover this use case.

    Version

    1.1

  5. object Try extends Serializable

Deprecated Value Members

  1. object MurmurHash

    An object designed to generate well-distributed non-cryptographic hashes.

    An object designed to generate well-distributed non-cryptographic hashes. It is designed to hash a collection of integers; along with the integers to hash, it generates two magic streams of integers to increase the distribution of repetitive input sequences. Thus, three methods need to be called at each step (to start and to incorporate a new integer) to update the values. Only one method needs to be called to finalize the hash.

    Annotations
    @deprecated
    Deprecated

    (Since version 2.10.0) use the object MurmurHash3 instead

Ungrouped