Scala Standard Library2.12.2-20170504-135222-21d12e9 < Back
 

# 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:

  - `scala.collection` and its sub-packages contain Scala's collections framework
    - `scala.collection.immutable` - Immutable, sequential data-structures such as `Vector`, `List`, `Range`, `HashMap` or `HashSet`
    - `scala.collection.mutable` - Mutable, sequential data-structures such as `ArrayBuffer`, `StringBuilder`, `HashMap` or `HashSet`
    - `scala.collection.concurrent` - Mutable, concurrent data-structures such as `TrieMap`
    - `scala.collection.parallel.immutable` - Immutable, parallel data-structures such as `ParVector`, `ParRange`, `ParHashMap` or `ParHashSet`
    - `scala.collection.parallel.mutable` - Mutable, parallel data-structures such as `ParArray`, `ParHashMap`, `ParTrieMap` or `ParHashSet`
  - `scala.concurrent` - Primitives for concurrent programming such as `Futures` and `Promises`
  - `scala.io` - Input and output operations
  - `scala.math` - Basic math functions and additional numeric types like `BigInt` and `BigDecimal`
  - `scala.sys` - Interaction with other processes and the operating system
  - `scala.util.matching` - Regular expressions

  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 meta

  When defining a field, the Scala compiler creates up to four accessors for it: a getter, a setter, and if the field is annotated with `@BeanProperty`, a bean getter and a bean setter.

  When defining a field, the Scala compiler creates up to four accessors for it: a getter, a setter, and if the field is annotated with `@BeanProperty`, a bean getter and a bean setter.

  For instance in the following class definition

      class C(@myAnnot @BeanProperty var c: Int)

  there are six entities which can carry the annotation `@myAnnot`: the constructor parameter, the generated field and the four accessors.

  By default, annotations on (`val`-, `var`- or plain) constructor parameters end up on the parameter, not on any other entity. Annotations on fields by default only end up on the field.

  The meta-annotations in package `scala.annotation.meta` are used to control where annotations on fields and class parameters are copied. This is done by annotating either the annotation type or the annotation class with one or several of the meta-annotations in this package.

  #### Annotating the annotation type

  The target meta-annotations can be put on the annotation type when instantiating the annotation. In the following example, the annotation `@Id` will be added only to the bean getter `getX`.

      import javax.persistence.Id
      class A {
        @(Id @beanGetter) @BeanProperty val x = 0
      }

  In order to annotate the field as well, the meta-annotation `@field` would need to be added.

  The syntax can be improved using a type alias:

      object ScalaJPA {
        type Id = javax.persistence.Id @beanGetter
      }
      import ScalaJPA.Id
      class A {
        @Id @BeanProperty val x = 0
      }

  #### Annotating the annotation class

  For annotations defined in Scala, a default target can be specified in the annotation class itself, for example

      @getter
      class myAnnotation extends Annotation

  This only changes the default target for the annotation `myAnnotation`. When instantiating the annotation, the target can still be specified as described in the last section.

-  package unchecked
- Annotation
- ClassfileAnnotation
- StaticAnnotation
- TypeConstraint
- compileTimeOnly
- elidable
- implicitAmbiguous
- implicitNotFound
- showAsInfix
- strictfp
- switch
- tailrec
- unspecialized
- varargs
-  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 `Future`s, 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

p

scala

# annotation 

#### package annotation

 
Ordering

1. Alphabetic

Visibility

1. Public
2. All

### Type Members

1.  abstract class Annotation extends AnyRef

   A base class for annotations.

   A base class for annotations. Annotations extending this class directly are not preserved for the Scala type checker and are also not stored as Java annotations in classfiles. To enable either or both of these, one needs to inherit from scala.annotation.StaticAnnotation or/and scala.annotation.ClassfileAnnotation.

   Version

     1.1, 2/02/2007

   Since

     2.4

2.  trait ClassfileAnnotation extends Annotation with StaticAnnotation

   A base class for classfile annotations.

   A base class for classfile annotations. These are stored as Java annotations] in classfiles.

   Version

     1.1, 2/02/2007

   Since

     2.4

3.  trait StaticAnnotation extends Annotation

   A base class for static annotations.

   A base class for static annotations. These are available to the Scala type checker, even across different compilation units.

   Version

     1.1, 2/02/2007

   Since

     2.4

4.  trait TypeConstraint extends Annotation

   A marker for annotations that, when applied to a type, should be treated as a constraint on the annotated type.

   A marker for annotations that, when applied to a type, should be treated as a constraint on the annotated type.

   A proper constraint should restrict the type based only on information mentioned within the type. A Scala compiler can use this assumption to rewrite the contents of the constraint as necessary. To contrast, a type annotation whose meaning depends on the context where it is written down is not a proper constrained type, and this marker should not be applied. A Scala compiler will drop such annotations in cases where it would rewrite a type constraint.

   Version

     1.1, 2007-11-5

   Since

     2.6

5.  final class compileTimeOnly extends Annotation with StaticAnnotation

   An annotation that designates that an annottee should not be referred to after type checking (which includes macro expansion).

   An annotation that designates that an annottee should not be referred to after type checking (which includes macro expansion).

   Examples of potential use: 1) The annottee can only appear in the arguments of some other macro that will eliminate it from the AST during expansion. 2) The annottee is a macro and should have been expanded away, so if hasn't, something wrong has happened. (Comes in handy to provide better support for new macro flavors, e.g. macro annotations, that can't be expanded by the vanilla compiler).

   Annotations
     @getter() @setter() @beanGetter() @beanSetter() @companionClass() @companionMethod()
   Since

     2.11.0

6.  final class elidable extends Annotation with StaticAnnotation

   An annotation for methods whose bodies may be excluded from compiler-generated bytecode.

   An annotation for methods whose bodies may be excluded from compiler-generated bytecode.

   Behavior is influenced by passing `-Xelide-below <arg>` to `scalac`. Calls to methods marked elidable (as well as the method body) will be omitted from generated code if the priority given the annotation is lower than that given on the command line.

       @elidable(123)           // annotation priority
       scalac -Xelide-below 456 // command line priority

   The method call will be replaced with an expression which depends on the type of the elided expression. In decreasing order of precedence:

       Unit            ()
       Boolean         false
       T <: AnyVal     0
       T >: Null       null
       T >: Nothing    Predef.???

   Complete example:

       import scala.annotation._, elidable._
       object Test extends App {
         def expensiveComputation(): Int = { Thread.sleep(1000) ; 172 }

         @elidable(WARNING) def warning(msg: String) = println(msg)
         @elidable(FINE) def debug(msg: String)      = println(msg)
         @elidable(FINE) def computedValue           = expensiveComputation()

         warning("Warning! Danger! Warning!")
         debug("Debug! Danger! Debug!")
         println("I computed a value: " + computedValue)
       }
       % scalac example.scala && scala Test
       Warning! Danger! Warning!
       Debug! Danger! Debug!
       I computed a value: 172

       // INFO lies between WARNING and FINE
       % scalac -Xelide-below INFO example.scala && scala Test
       Warning! Danger! Warning!
       I computed a value: 0

   Since

     2.8

7.  final class implicitAmbiguous extends Annotation with StaticAnnotation

   To customize the error message that's emitted when an implicit search finds multiple ambiguous values, annotate at least one of the implicit values `@implicitAmbiguous`.

   To customize the error message that's emitted when an implicit search finds multiple ambiguous values, annotate at least one of the implicit values `@implicitAmbiguous`. Assuming the implicit value is a method with type parameters `X1,..., XN`, the error message will be the result of replacing all occurrences of `${Xi}` in the string `msg` with the string representation of the corresponding type argument `Ti`.

   If more than one `@implicitAmbiguous` annotation is collected, the compiler is free to pick any of them to display.

   Nice errors can direct users to fix imports or even tell them why code intentionally doesn't compile.

       trait =!=[C, D]

       implicit def neq[E, F] : E =!= F = null

       @annotation.implicitAmbiguous("Could not prove ${J} =!= ${J}")
       implicit def neqAmbig1[G, H, J] : J =!= J = null
       implicit def neqAmbig2[I] : I =!= I = null

       implicitly[Int =!= Int]

   Since

     2.12.0

8.  final class implicitNotFound extends Annotation with StaticAnnotation

   To customize the error message that's emitted when an implicit of type C[T1,..., TN] cannot be found, annotate the class C with @implicitNotFound.

   To customize the error message that's emitted when an implicit of type C[T1,..., TN] cannot be found, annotate the class C with @implicitNotFound. Assuming C has type parameters X1,..., XN, the error message will be the result of replacing all occurrences of ${Xi} in the string msg with the string representation of the corresponding type argument Ti. *

   Since

     2.8.1

9.  class showAsInfix extends Annotation with StaticAnnotation

   This annotation configures how Scala prints two-parameter generic types.

   This annotation configures how Scala prints two-parameter generic types.

   By default, types with symbolic names are printed infix; while types without them are printed using the regular generic type syntax.

   Example of usage:

       scala> class Map[T, U]
       defined class Map

       scala> def foo: Int Map Int = ???
       foo: Map[Int,Int]

       scala> @showAsInfix class Map[T, U]
       defined class Map

       scala> def foo: Int Map Int = ???
       foo: Int Map Int

   Since

     2.12.2

10.  class strictfp extends Annotation with StaticAnnotation

    If this annotation is present on a method or its enclosing class, the strictfp flag will be emitted.

    If this annotation is present on a method or its enclosing class, the strictfp flag will be emitted.

    Version

      2.9

    Since

      2.9

11.  final class switch extends Annotation with StaticAnnotation

    An annotation to be applied to a match expression.

    An annotation to be applied to a match expression. If present, the compiler will verify that the match has been compiled to a tableswitch or lookupswitch and issue an error if it instead compiles into a series of conditional expressions. Example usage:

        val Constant = 'Q'
        def tokenMe(ch: Char) = (ch: @switch) match {
          case ' ' | '\t' | '\n'  => 1
          case 'A' | 'Z' | '$'    => 2
          case '5' | Constant     => 3  // a non-literal may prevent switch generation: this would not compile
          case _                  => 4
        }

    Note: for pattern matches with one or two cases, the compiler generates jump instructions. Annotating such a match with `@switch` does not issue any warning.

    Since

      2.8

12.  final class tailrec extends Annotation with StaticAnnotation

    A method annotation which verifies that the method will be compiled with tail call optimization.

    A method annotation which verifies that the method will be compiled with tail call optimization.

    If it is present, the compiler will issue an error if the method cannot be optimized into a loop.

    Since

      2.8

13.  class unspecialized extends Annotation with StaticAnnotation

    A method annotation which suppresses the creation of additional specialized forms based on enclosing specialized type parameters.

    A method annotation which suppresses the creation of additional specialized forms based on enclosing specialized type parameters.

    Since

      2.10

14.  final class varargs extends Annotation with StaticAnnotation

    A method annotation which instructs the compiler to generate a Java varargs-style forwarder method for interop.

    A method annotation which instructs the compiler to generate a Java varargs-style forwarder method for interop. This annotation can only be applied to methods with repeated parameters.

    Since

      2.9

### Value Members

1.  object elidable

   This useless appearing code was necessary to allow people to use named constants for the elidable annotation.

   This useless appearing code was necessary to allow people to use named constants for the elidable annotation. This is what it takes to convince the compiler to fold the constants: otherwise when it's time to check an elision level it's staring at a tree like

       (Select(Level, Select(FINEST, Apply(intValue, Nil))))

   instead of the number `300`.

   Since

     2.8

### Ungrouped