scala
package scala
Core Scala types. They are always available without an explicit import.
- Source
- package.scala
- Alphabetic
- By Inheritance
- scala
- AnyRef
- Any
- Hide All
- Show All
- Public
- Protected
Package Members
- package annotation
- package beans
- package collection
- package compat
- 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 https://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 implicitExecutionContext
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 words = Files.readAllLines("/etc/dictionaries-common/words").asScala words.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") }
- package io
- package jdk
The jdk package contains utilities to interact with JDK classes.
The jdk package contains utilities to interact with JDK classes.
This packages offers a number of converters, that are able to wrap or copy types from the scala library to equivalent types in the JDK class library and vice versa:
- CollectionConverters, converting collections like scala.collection.Seq, scala.collection.Map, scala.collection.Set, scala.collection.mutable.Buffer, scala.collection.Iterator and scala.collection.Iterable to their JDK counterparts
- OptionConverters, converting between Option and java.util.Optional and primitive variations
- StreamConverters, to create JDK Streams from scala collections
- DurationConverters, for conversions between scala scala.concurrent.duration.FiniteDuration and java.time.Duration
- FunctionConverters, from scala Functions to java java.util.function.Function, java.util.function.UnaryOperator, java.util.function.Consumer and java.util.function.Predicate, as well as primitive variations and Bi-variations.
By convention, converters that wrap an object to provide a different interface to the same underlying data structure use .asScala and .asJava extension methods, whereas converters that copy the underlying data structure use .toScala and .toJava.
In the javaapi package, the same converters can be found with a java-friendly interface that don't rely on implicit enrichments.
Additionally, this package offers Accumulators, capable of efficiently traversing JDK Streams.
- 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.
- See also
- package ref
- package reflect
- 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. - package util
Type Members
- type ::[+A] = scala.collection.immutable.::[A]
- sealed abstract class <:<[-From, +To] extends (From) => To with Serializable
An instance of
A <:< B
witnesses thatA
is a subtype ofB
.An instance of
A <:< B
witnesses thatA
is a subtype ofB
. Requiring an implicit argument of the typeA <:< B
encodes the generalized constraintA <: B
.To constrain any abstract type
T
that's in scope in a method's argument list (not just the method's own type parameters) simply add an implicit argument of typeT <:< U
, whereU
is the required upper bound; or for lower-bounds, use:L <:< T
, whereL
is the required lower bound.In case of any confusion over which method goes in what direction, all the "Co" methods (including apply) go from left to right in the type ("with" the type), and all the "Contra" methods go from right to left ("against" the type). E.g., apply turns a
From
into aTo
, and substituteContra replaces theTo
s in a type withFrom
s.In part contributed by Jason Zaugg.
- From
a type which is proved a subtype of
To
- To
a type which is proved a supertype of
From
- Annotations
- @implicitNotFound()
sealed trait Option[+A] { // def flatten[B, A <: Option[B]]: Option[B] = ... // won't work, since the A in flatten shadows the class-scoped A. def flatten[B](implicit ev: A <:< Option[B]): Option[B] = if(isEmpty) None else ev(get) // Because (A <:< Option[B]) <: (A => Option[B]), ev can be called to turn the // A from get into an Option[B], and because ev is implicit, that call can be // left out and inserted automatically. }
- See also
=:= for expressing equality constraints
Example: - sealed abstract class =:=[From, To] extends <:<[From, To] with Serializable
An instance of
A =:= B
witnesses that the typesA
andB
are equal.An instance of
A =:= B
witnesses that the typesA
andB
are equal. It also acts as aA <:< B
, but not aB <:< A
(directly) due to restrictions on subclassing.In case of any confusion over which method goes in what direction, all the "Co" methods (including apply) go from left to right in the type ("with" the type), and all the "Contra" methods go from right to left ("against" the type). E.g., apply turns a
From
into aTo
, and substituteContra replaces theTo
s in a type withFrom
s.- From
a type which is proved equal to
To
- To
a type which is proved equal to
From
- Annotations
- @implicitNotFound()
An in-place variant of scala.collection.mutable.ArrayBuffer#transpose
implicit class BufOps[A](private val buf: ArrayBuffer[A]) extends AnyVal { def inPlaceTranspose[E]()(implicit ev: A =:= ArrayBuffer[E]) = ??? // Because ArrayBuffer is invariant, we can't make do with just a A <:< ArrayBuffer[E] // Getting buffers *out* from buf would work, but adding them back *in* wouldn't. }
- See also
<:< for expressing subtyping constraints
Example: - type AbstractMethodError = java.lang.AbstractMethodError
- abstract class Any
Class
Any
is the root of the Scala class hierarchy.Class
Any
is the root of the Scala class hierarchy. Every class in a Scala execution environment inherits directly or indirectly from this class.Starting with Scala 2.10 it is possible to directly extend
Any
using universal traits. A universal trait is a trait that extendsAny
, only hasdef
s as members, and does no initialization.The main use case for universal traits is to allow basic inheritance of methods for value classes. For example,
trait Printable extends Any { def print(): Unit = println(this) } class Wrapper(val underlying: Int) extends AnyVal with Printable val w = new Wrapper(3) w.print()
See the Value Classes and Universal Traits for more details on the interplay of universal traits and value classes.
- abstract class AnyVal extends Any
AnyVal
is the root class of all value types, which describe values not implemented as objects in the underlying host system.AnyVal
is the root class of all value types, which describe values not implemented as objects in the underlying host system. Value classes are specified in Scala Language Specification, section 12.2.The standard implementation includes nine
AnyVal
subtypes:scala.Double, scala.Float, scala.Long, scala.Int, scala.Char, scala.Short, and scala.Byte are the numeric value types.
scala.Unit and scala.Boolean are the non-numeric value types.
Other groupings:
- The subrange types are scala.Byte, scala.Short, and scala.Char.
- The integer types include the subrange types as well as scala.Int and scala.Long.
- The floating point types are scala.Float and scala.Double.
Prior to Scala 2.10,
AnyVal
was a sealed trait. Beginning with Scala 2.10, however, it is possible to define a subclass ofAnyVal
called a user-defined value class which is treated specially by the compiler. Properly-defined user value classes provide a way to improve performance on user-defined types by avoiding object allocation at runtime, and by replacing virtual method invocations with static method invocations.User-defined value classes which avoid object allocation...
- must have a single
val
parameter that is the underlying runtime representation. - can define
def
s, but noval
s,var
s, or nestedtrait
s,class
es orobject
s. - typically extend no other trait apart from
AnyVal
. - cannot be used in type tests or pattern matching.
- may not override
equals
orhashCode
methods.
A minimal example:
class Wrapper(val underlying: Int) extends AnyVal { def foo: Wrapper = new Wrapper(underlying * 19) }
It's important to note that user-defined value classes are limited, and in some circumstances, still must allocate a value class instance at runtime. These limitations and circumstances are explained in greater detail in the Value Classes and Universal Traits.
- trait App extends DelayedInit
The
App
trait can be used to quickly turn objects into executable programs.The
App
trait can be used to quickly turn objects into executable programs. Here is an example:object Main extends App { Console.println("Hello World: " + (args mkString ", ")) }
No explicit
main
method is needed. Instead, the whole class body becomes the “main method”.args
returns the current command line arguments as an array.Caveats
It should be noted that this trait is implemented using the DelayedInit functionality, which means that fields of the object will not have been initialized before the main method has been executed.
Future versions of this trait will no longer extend
DelayedInit
.In Scala 3, the
DelayedInit
feature was dropped.App
exists only in a limited form that also does not support command line arguments and will be deprecated in the future.@main methods are the recommended scheme to generate programs that can be invoked from the command line in Scala 3.
@main def runMyProgram(args: String*): Unit = { // your program here }
If programs need to cross-build between Scala 2 and Scala 3, it is recommended to use an explicit
main
method:object Main { def main(args: Array[String]): Unit = { // your program here } }
- Annotations
- @nowarn()
- final class Array[T] extends java.io.Serializable with java.lang.Cloneable
Arrays are mutable, indexed collections of values.
Arrays are mutable, indexed collections of values.
Array[T]
is Scala's representation for Java'sT[]
.val numbers = Array(1, 2, 3, 4) val first = numbers(0) // read the first element numbers(3) = 100 // replace the 4th array element with 100 val biggerNumbers = numbers.map(_ * 2) // multiply all numbers by two
Arrays make use of two common pieces of Scala syntactic sugar, shown on lines 2 and 3 of the above example code. Line 2 is translated into a call to
apply(Int)
, while line 3 is translated into a call toupdate(Int, T)
.Two implicit conversions exist in scala.Predef that are frequently applied to arrays: a conversion to scala.collection.ArrayOps (shown on line 4 of the example above) and a conversion to scala.collection.mutable.ArraySeq (a subtype of scala.collection.Seq). Both types make available many of the standard operations found in the Scala collections API. The conversion to
ArrayOps
is temporary, as all operations defined onArrayOps
return anArray
, while the conversion toArraySeq
is permanent as all operations return aArraySeq
.The conversion to
ArrayOps
takes priority over the conversion toArraySeq
. For instance, consider the following code:val arr = Array(1, 2, 3) val arrReversed = arr.reverse val seqReversed : collection.Seq[Int] = arr.reverse
Value
arrReversed
will be of typeArray[Int]
, with an implicit conversion toArrayOps
occurring to perform thereverse
operation. The value ofseqReversed
, on the other hand, will be computed by converting toArraySeq
first and invoking the variant ofreverse
that returns anotherArraySeq
.- See also
Scala Language Specification, for in-depth information on the transformations the Scala compiler makes on Arrays (Sections 6.6 and 6.15 respectively.)
"Scala 2.8 Arrays" the Scala Improvement Document detailing arrays since Scala 2.8.
"The Scala 2.8 Collections' API" section on
Array
by Martin Odersky for more information.
- type ArrayIndexOutOfBoundsException = java.lang.ArrayIndexOutOfBoundsException
- type BigDecimal = scala.math.BigDecimal
- type BigInt = scala.math.BigInt
- abstract final class Boolean extends AnyVal
Boolean
(equivalent to Java'sboolean
primitive type) is a subtype of scala.AnyVal.Boolean
(equivalent to Java'sboolean
primitive type) is a subtype of scala.AnyVal. Instances ofBoolean
are not represented by an object in the underlying runtime system.There is an implicit conversion from scala.Boolean => scala.runtime.RichBoolean which provides useful non-primitive operations.
- abstract final class Byte extends AnyVal
Byte
, a 8-bit signed integer (equivalent to Java'sbyte
primitive type) is a subtype of scala.AnyVal.Byte
, a 8-bit signed integer (equivalent to Java'sbyte
primitive type) is a subtype of scala.AnyVal. Instances ofByte
are not represented by an object in the underlying runtime system.There is an implicit conversion from scala.Byte => scala.runtime.RichByte which provides useful non-primitive operations.
- abstract final class Char extends AnyVal
Char
, a 16-bit unsigned integer (equivalent to Java'schar
primitive type) is a subtype of scala.AnyVal.Char
, a 16-bit unsigned integer (equivalent to Java'schar
primitive type) is a subtype of scala.AnyVal. Instances ofChar
are not represented by an object in the underlying runtime system.There is an implicit conversion from scala.Char => scala.runtime.RichChar which provides useful non-primitive operations.
- type ClassCastException = java.lang.ClassCastException
- type Cloneable = java.lang.Cloneable
- abstract final class Double extends AnyVal
Double
, a 64-bit IEEE-754 floating point number (equivalent to Java'sdouble
primitive type) is a subtype of scala.AnyVal.Double
, a 64-bit IEEE-754 floating point number (equivalent to Java'sdouble
primitive type) is a subtype of scala.AnyVal. Instances ofDouble
are not represented by an object in the underlying runtime system.There is an implicit conversion from scala.Double => scala.runtime.RichDouble which provides useful non-primitive operations.
- final class DummyImplicit extends AnyRef
A type for which there is always an implicit value.
- trait Dynamic extends Any
A marker trait that enables dynamic invocations.
A marker trait that enables dynamic invocations. Instances
x
of this trait allow method invocationsx.meth(args)
for arbitrary method namesmeth
and argument listsargs
as well as field accessesx.field
for arbitrary field namesfield
.If a call is not natively supported by
x
(i.e. if type checking fails), it is rewritten according to the following rules:foo.method("blah") ~~> foo.applyDynamic("method")("blah") foo.method(x = "blah") ~~> foo.applyDynamicNamed("method")(("x", "blah")) foo.method(x = 1, 2) ~~> foo.applyDynamicNamed("method")(("x", 1), ("", 2)) foo.field ~~> foo.selectDynamic("field") foo.varia = 10 ~~> foo.updateDynamic("varia")(10) foo.arr(10) = 13 ~~> foo.selectDynamic("arr").update(10, 13) foo.arr(10) ~~> foo.applyDynamic("arr")(10)
As of Scala 2.10, defining direct or indirect subclasses of this trait is only possible if the language feature
dynamics
is enabled. - type Either[+A, +B] = scala.util.Either[A, B]
- abstract class Enumeration extends Serializable
Defines a finite set of values specific to the enumeration.
Defines a finite set of values specific to the enumeration. Typically these values enumerate all possible forms something can take and provide a lightweight alternative to case classes.
Each call to a
Value
method adds a new unique value to the enumeration. To be accessible, these values are usually defined asval
members of the enumeration.All values in an enumeration share a common, unique type defined as the
Value
type member of the enumeration (Value
selected on the stable identifier path of the enumeration instance).Values SHOULD NOT be added to an enumeration after its construction; doing so makes the enumeration thread-unsafe. If values are added to an enumeration from multiple threads (in a non-synchronized fashion) after construction, the behavior of the enumeration is undefined.
- Annotations
- @SerialVersionUID()
// Define a new enumeration with a type alias and work with the full set of enumerated values object WeekDay extends Enumeration { type WeekDay = Value val Mon, Tue, Wed, Thu, Fri, Sat, Sun = Value } import WeekDay._ def isWorkingDay(d: WeekDay) = ! (d == Sat || d == Sun) WeekDay.values filter isWorkingDay foreach println // output: // Mon // Tue // Wed // Thu // Fri
, // Example of adding attributes to an enumeration by extending the Enumeration.Val class object Planet extends Enumeration { protected case class PlanetVal(mass: Double, radius: Double) extends super.Val { def surfaceGravity: Double = Planet.G * mass / (radius * radius) def surfaceWeight(otherMass: Double): Double = otherMass * surfaceGravity } import scala.language.implicitConversions implicit def valueToPlanetVal(x: Value): PlanetVal = x.asInstanceOf[PlanetVal] val G: Double = 6.67300E-11 val Mercury = PlanetVal(3.303e+23, 2.4397e6) val Venus = PlanetVal(4.869e+24, 6.0518e6) val Earth = PlanetVal(5.976e+24, 6.37814e6) val Mars = PlanetVal(6.421e+23, 3.3972e6) val Jupiter = PlanetVal(1.9e+27, 7.1492e7) val Saturn = PlanetVal(5.688e+26, 6.0268e7) val Uranus = PlanetVal(8.686e+25, 2.5559e7) val Neptune = PlanetVal(1.024e+26, 2.4746e7) } println(Planet.values.filter(_.radius > 7.0e6)) // output: // Planet.ValueSet(Jupiter, Saturn, Uranus, Neptune)
Examples: - trait Equals extends Any
An interface containing operations for equality.
An interface containing operations for equality. The only method not already present in class
AnyRef
iscanEqual
. - type Equiv[T] = scala.math.Equiv[T]
- type Error = java.lang.Error
- type Exception = java.lang.Exception
- abstract final class Float extends AnyVal
Float
, a 32-bit IEEE-754 floating point number (equivalent to Java'sfloat
primitive type) is a subtype of scala.AnyVal.Float
, a 32-bit IEEE-754 floating point number (equivalent to Java'sfloat
primitive type) is a subtype of scala.AnyVal. Instances ofFloat
are not represented by an object in the underlying runtime system.There is an implicit conversion from scala.Float => scala.runtime.RichFloat which provides useful non-primitive operations.
- type Fractional[T] = scala.math.Fractional[T]
- trait Function0[+R] extends AnyRef
A function of 0 parameters.
A function of 0 parameters.
In the following example, the definition of
greeting
is shorthand, conceptually, for the anonymous class definitionanonfun0
, although the implementation details of how the function value is constructed may differ:object Main extends App { val name = "world" val greeting = () => s"hello, $name" val anonfun0 = new Function0[String] { def apply(): String = s"hello, $name" } assert(greeting() == anonfun0()) }
- trait Function1[-T1, +R] extends AnyRef
A function of 1 parameter.
A function of 1 parameter.
In the following example, the definition of
succ
is shorthand, conceptually, for the anonymous class definitionanonfun1
, although the implementation details of how the function value is constructed may differ:object Main extends App { val succ = (x: Int) => x + 1 val anonfun1 = new Function1[Int, Int] { def apply(x: Int): Int = x + 1 } assert(succ(0) == anonfun1(0)) }
Note that the difference between
Function1
and scala.PartialFunction is that the latter can specify inputs which it will not handle.- Annotations
- @implicitNotFound()
- trait Function10[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, +R] extends AnyRef
A function of 10 parameters.
- trait Function11[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, +R] extends AnyRef
A function of 11 parameters.
- trait Function12[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, +R] extends AnyRef
A function of 12 parameters.
- trait Function13[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, +R] extends AnyRef
A function of 13 parameters.
- trait Function14[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, -T14, +R] extends AnyRef
A function of 14 parameters.
- trait Function15[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, -T14, -T15, +R] extends AnyRef
A function of 15 parameters.
- trait Function16[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, -T14, -T15, -T16, +R] extends AnyRef
A function of 16 parameters.
- trait Function17[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, -T14, -T15, -T16, -T17, +R] extends AnyRef
A function of 17 parameters.
- trait Function18[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, -T14, -T15, -T16, -T17, -T18, +R] extends AnyRef
A function of 18 parameters.
- trait Function19[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, -T14, -T15, -T16, -T17, -T18, -T19, +R] extends AnyRef
A function of 19 parameters.
- trait Function2[-T1, -T2, +R] extends AnyRef
A function of 2 parameters.
A function of 2 parameters.
In the following example, the definition of
max
is shorthand, conceptually, for the anonymous class definitionanonfun2
, although the implementation details of how the function value is constructed may differ:object Main extends App { val max = (x: Int, y: Int) => if (x < y) y else x val anonfun2 = new Function2[Int, Int, Int] { def apply(x: Int, y: Int): Int = if (x < y) y else x } assert(max(0, 1) == anonfun2(0, 1)) }
- trait Function20[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, -T14, -T15, -T16, -T17, -T18, -T19, -T20, +R] extends AnyRef
A function of 20 parameters.
- trait Function21[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, -T14, -T15, -T16, -T17, -T18, -T19, -T20, -T21, +R] extends AnyRef
A function of 21 parameters.
- trait Function22[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, -T14, -T15, -T16, -T17, -T18, -T19, -T20, -T21, -T22, +R] extends AnyRef
A function of 22 parameters.
- trait Function3[-T1, -T2, -T3, +R] extends AnyRef
A function of 3 parameters.
- trait Function4[-T1, -T2, -T3, -T4, +R] extends AnyRef
A function of 4 parameters.
- trait Function5[-T1, -T2, -T3, -T4, -T5, +R] extends AnyRef
A function of 5 parameters.
- trait Function6[-T1, -T2, -T3, -T4, -T5, -T6, +R] extends AnyRef
A function of 6 parameters.
- trait Function7[-T1, -T2, -T3, -T4, -T5, -T6, -T7, +R] extends AnyRef
A function of 7 parameters.
- trait Function8[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, +R] extends AnyRef
A function of 8 parameters.
- trait Function9[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, +R] extends AnyRef
A function of 9 parameters.
- type IllegalArgumentException = java.lang.IllegalArgumentException
- type IndexOutOfBoundsException = java.lang.IndexOutOfBoundsException
- type IndexedSeq[+A] = scala.collection.immutable.IndexedSeq[A]
- Annotations
- @migration
- Migration
(Changed in version 2.13.0) scala.IndexedSeq is now scala.collection.immutable.IndexedSeq instead of scala.collection.IndexedSeq
- abstract final class Int extends AnyVal
Int
, a 32-bit signed integer (equivalent to Java'sint
primitive type) is a subtype of scala.AnyVal.Int
, a 32-bit signed integer (equivalent to Java'sint
primitive type) is a subtype of scala.AnyVal. Instances ofInt
are not represented by an object in the underlying runtime system.There is an implicit conversion from scala.Int => scala.runtime.RichInt which provides useful non-primitive operations.
- type Integral[T] = scala.math.Integral[T]
- type InterruptedException = java.lang.InterruptedException
- type Iterable[+A] = scala.collection.Iterable[A]
- type IterableOnce[+A] = scala.collection.IterableOnce[A]
- type Iterator[+A] = scala.collection.Iterator[A]
- type LazyList[+A] = scala.collection.immutable.LazyList[A]
- type Left[+A, +B] = scala.util.Left[A, B]
- type List[+A] = scala.collection.immutable.List[A]
- abstract final class Long extends AnyVal
Long
, a 64-bit signed integer (equivalent to Java'slong
primitive type) is a subtype of scala.AnyVal.Long
, a 64-bit signed integer (equivalent to Java'slong
primitive type) is a subtype of scala.AnyVal. Instances ofLong
are not represented by an object in the underlying runtime system.There is an implicit conversion from scala.Long => scala.runtime.RichLong which provides useful non-primitive operations.
- final class MatchError extends RuntimeException
This class implements errors which are thrown whenever an object doesn't match any pattern of a pattern matching expression.
- type NoSuchElementException = java.util.NoSuchElementException
- final class NotImplementedError extends Error
Throwing this exception can be a temporary replacement for a method body that remains to be implemented.
Throwing this exception can be a temporary replacement for a method body that remains to be implemented. For instance, the exception is thrown by
Predef.???
. - abstract final class Nothing extends Any
Nothing
is - together with scala.Null - at the bottom of Scala's type hierarchy.Nothing
is - together with scala.Null - at the bottom of Scala's type hierarchy.Nothing
is a subtype of every other type (including scala.Null); there exist no instances of this type. Although typeNothing
is uninhabited, it is nevertheless useful in several ways. For instance, the Scala library defines a value scala.collection.immutable.Nil of typeList[Nothing]
. Because lists are covariant in Scala, this makes scala.collection.immutable.Nil an instance ofList[T]
, for any element of typeT
.Another usage for Nothing is the return type for methods which never return normally. One example is method error in scala.sys, which always throws an exception.
- abstract final class Null extends AnyRef
Null
is - together with scala.Nothing - at the bottom of the Scala type hierarchy.Null
is - together with scala.Nothing - at the bottom of the Scala type hierarchy.Null
is the type of thenull
literal. It is a subtype of every type except those of value classes. Value classes are subclasses of AnyVal, which includes primitive types such as Int, Boolean, and user-defined value classes.Since
Null
is not a subtype of value types,null
is not a member of any such type. For instance, it is not possible to assignnull
to a variable of type scala.Int. - type NullPointerException = java.lang.NullPointerException
- type NumberFormatException = java.lang.NumberFormatException
- type Numeric[T] = scala.math.Numeric[T]
- sealed abstract class Option[+A] extends IterableOnce[A] with Product with Serializable
Represents optional values.
Represents optional values. Instances of
Option
are either an instance of scala.Some or the objectNone
.The most idiomatic way to use an scala.Option instance is to treat it as a collection or monad and use
map
,flatMap
,filter
, orforeach
:val name: Option[String] = request getParameter "name" val upper = name map { _.trim } filter { _.length != 0 } map { _.toUpperCase } println(upper getOrElse "")
Note that this is equivalent to
val upper = for { name <- request getParameter "name" trimmed <- Some(name.trim) upper <- Some(trimmed.toUpperCase) if trimmed.length != 0 } yield upper println(upper getOrElse "")
Because of how for comprehension works, if
None
is returned fromrequest.getParameter
, the entire expression results inNone
This allows for sophisticated chaining of scala.Option values without having to check for the existence of a value.
These are useful methods that exist for both scala.Some and
None
.- isDefined — True if not empty
- isEmpty — True if empty
- nonEmpty — True if not empty
- orElse — Evaluate and return alternate optional value if empty
- getOrElse — Evaluate and return alternate value if empty
- get — Return value, throw exception if empty
- fold — Apply function on optional value, return default if empty
- map — Apply a function on the optional value
- flatMap — Same as map but function must return an optional value
- foreach — Apply a procedure on option value
- collect — Apply partial pattern match on optional value
- filter — An optional value satisfies predicate
- filterNot — An optional value doesn't satisfy predicate
- exists — Apply predicate on optional value, or false if empty
- forall — Apply predicate on optional value, or true if empty
- contains — Checks if value equals optional value, or false if empty
- zip — Combine two optional values to make a paired optional value
- unzip — Split an optional pair to two optional values
- unzip3 — Split an optional triple to three optional values
- toList — Unary list of optional value, otherwise the empty list
A less-idiomatic way to use scala.Option values is via pattern matching:
val nameMaybe = request getParameter "name" nameMaybe match { case Some(name) => println(name.trim.toUppercase) case None => println("No name value") }
Interacting with code that can occasionally return null can be safely wrapped in scala.Option to become
None
and scala.Some otherwise.val abc = new java.util.HashMap[Int, String] abc.put(1, "A") bMaybe = Option(abc.get(2)) bMaybe match { case Some(b) => println(s"Found $b") case None => println("Not found") }
- Annotations
- @SerialVersionUID()
- Note
Many of the methods in here are duplicative with those in the Iterable hierarchy, but they are duplicated for a reason: the implicit conversion tends to leave one with an Iterable in situations where one could have retained an Option.
- type Ordered[T] = scala.math.Ordered[T]
- type Ordering[T] = scala.math.Ordering[T]
- trait PartialFunction[-A, +B] extends (A) => B
A partial function of type
PartialFunction[A, B]
is a unary function where the domain does not necessarily include all values of typeA
.A partial function of type
PartialFunction[A, B]
is a unary function where the domain does not necessarily include all values of typeA
. The function isDefinedAt allows to test dynamically if a value is in the domain of the function.Even if
isDefinedAt
returns true for ana: A
, callingapply(a)
may still throw an exception, so the following code is legal:val f: PartialFunction[Int, Any] = { case x => x / 0 } // ArithmeticException: / by zero
It is the responsibility of the caller to call
isDefinedAt
before callingapply
, because ifisDefinedAt
is false, it is not guaranteedapply
will throw an exception to indicate an error condition. If an exception is not thrown, evaluation may result in an arbitrary value.The usual way to respect this contract is to call applyOrElse, which is expected to be more efficient than calling both
isDefinedAt
andapply
.The main distinction between
PartialFunction
and scala.Function1 is that the user of aPartialFunction
may choose to do something different with input that is declared to be outside its domain. For example:val sample = 1 to 10 def isEven(n: Int) = n % 2 == 0 val eveningNews: PartialFunction[Int, String] = { case x if isEven(x) => s"$x is even" } // The method collect is described as "filter + map" // because it uses a PartialFunction to select elements // to which the function is applied. val evenNumbers = sample.collect(eveningNews) val oddlyEnough: PartialFunction[Int, String] = { case x if !isEven(x) => s"$x is odd" } // The method orElse allows chaining another PartialFunction // to handle input outside the declared domain. val numbers = sample.map(eveningNews orElse oddlyEnough) // same as val numbers = sample.map(n => eveningNews.applyOrElse(n, oddlyEnough)) val half: PartialFunction[Int, Int] = { case x if isEven(x) => x / 2 } // Calculating the domain of a composition can be expensive. val oddByHalf = half.andThen(oddlyEnough) // Invokes `half.apply` on even elements! val oddBalls = sample.filter(oddByHalf.isDefinedAt) // Better than filter(oddByHalf.isDefinedAt).map(oddByHalf) val oddBalls = sample.collect(oddByHalf) // Providing "default" values. val oddsAndEnds = sample.map(n => oddByHalf.applyOrElse(n, (i: Int) => s"[$i]"))
- Note
Optional Functions, PartialFunctions and extractor objects can be converted to each other as shown in the following table.
How to convert ...
to a PartialFunction
to an optional Function
to an extractor
from a PartialFunction
from optional Function
from an extractor
{ case extractor(x) => x }
extractor.unapply _
- type PartialOrdering[T] = scala.math.PartialOrdering[T]
- type PartiallyOrdered[T] = scala.math.PartiallyOrdered[T]
- trait Product extends Equals
Base trait for all products, which in the standard library include at least scala.Product1 through scala.Product22 and therefore also their subclasses scala.Tuple1 through scala.Tuple22.
Base trait for all products, which in the standard library include at least scala.Product1 through scala.Product22 and therefore also their subclasses scala.Tuple1 through scala.Tuple22. In addition, all case classes implement
Product
with synthetically generated methods. - trait Product1[+T1] extends Product
Product1 is a Cartesian product of 1 component.
- trait Product10[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10] extends Product
Product10 is a Cartesian product of 10 components.
- trait Product11[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11] extends Product
Product11 is a Cartesian product of 11 components.
- trait Product12[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12] extends Product
Product12 is a Cartesian product of 12 components.
- trait Product13[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13] extends Product
Product13 is a Cartesian product of 13 components.
- trait Product14[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14] extends Product
Product14 is a Cartesian product of 14 components.
- trait Product15[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15] extends Product
Product15 is a Cartesian product of 15 components.
- trait Product16[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16] extends Product
Product16 is a Cartesian product of 16 components.
- trait Product17[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17] extends Product
Product17 is a Cartesian product of 17 components.
- trait Product18[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17, +T18] extends Product
Product18 is a Cartesian product of 18 components.
- trait Product19[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17, +T18, +T19] extends Product
Product19 is a Cartesian product of 19 components.
- trait Product2[+T1, +T2] extends Product
Product2 is a Cartesian product of 2 components.
- trait Product20[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17, +T18, +T19, +T20] extends Product
Product20 is a Cartesian product of 20 components.
- trait Product21[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17, +T18, +T19, +T20, +T21] extends Product
Product21 is a Cartesian product of 21 components.
- trait Product22[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17, +T18, +T19, +T20, +T21, +T22] extends Product
Product22 is a Cartesian product of 22 components.
- trait Product3[+T1, +T2, +T3] extends Product
Product3 is a Cartesian product of 3 components.
- trait Product4[+T1, +T2, +T3, +T4] extends Product
Product4 is a Cartesian product of 4 components.
- trait Product5[+T1, +T2, +T3, +T4, +T5] extends Product
Product5 is a Cartesian product of 5 components.
- trait Product6[+T1, +T2, +T3, +T4, +T5, +T6] extends Product
Product6 is a Cartesian product of 6 components.
- trait Product7[+T1, +T2, +T3, +T4, +T5, +T6, +T7] extends Product
Product7 is a Cartesian product of 7 components.
- trait Product8[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8] extends Product
Product8 is a Cartesian product of 8 components.
- trait Product9[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9] extends Product
Product9 is a Cartesian product of 9 components.
- type Range = scala.collection.immutable.Range
- type Right[+A, +B] = scala.util.Right[A, B]
- type RuntimeException = java.lang.RuntimeException
- case class ScalaReflectionException(msg: String) extends Exception with Product with Serializable
An exception that indicates an error during Scala reflection
- type Seq[+A] = scala.collection.immutable.Seq[A]
- Annotations
- @migration
- Migration
(Changed in version 2.13.0) scala.Seq is now scala.collection.immutable.Seq instead of scala.collection.Seq
- class SerialVersionUID extends Annotation with ConstantAnnotation
Annotation for specifying the
serialVersionUID
field of a (serializable) class.Annotation for specifying the
serialVersionUID
field of a (serializable) class.On the JVM, a class with this annotation will receive a
private
,static
, andfinal
field calledserialVersionUID
with the providedvalue
, which the JVM's serialization mechanism uses to determine serialization compatibility between different versions of a class.- Annotations
- @deprecatedInheritance()
- See also
- type Serializable = java.io.Serializable
- abstract final class Short extends AnyVal
Short
, a 16-bit signed integer (equivalent to Java'sshort
primitive type) is a subtype of scala.AnyVal.Short
, a 16-bit signed integer (equivalent to Java'sshort
primitive type) is a subtype of scala.AnyVal. Instances ofShort
are not represented by an object in the underlying runtime system.There is an implicit conversion from scala.Short => scala.runtime.RichShort which provides useful non-primitive operations.
- final trait Singleton extends Any
Singleton
is used by the compiler as a supertype for singleton types.Singleton
is used by the compiler as a supertype for singleton types. This includes literal types, as they are also singleton types.scala> object A { val x = 42 } defined object A scala> implicitly[A.type <:< Singleton] res12: A.type <:< Singleton = generalized constraint scala> implicitly[A.x.type <:< Singleton] res13: A.x.type <:< Singleton = generalized constraint scala> implicitly[42 <:< Singleton] res14: 42 <:< Singleton = generalized constraint scala> implicitly[Int <:< Singleton] ^ error: Cannot prove that Int <:< Singleton.
Singleton
has a special meaning when it appears as an upper bound on a formal type parameter. Normally, type inference in Scala widens singleton types to the underlying non-singleton type. When a type parameter has an explicit upper bound ofSingleton
, the compiler infers a singleton type.scala> def check42[T](x: T)(implicit ev: T =:= 42): T = x check42: [T](x: T)(implicit ev: T =:= 42)T scala> val x1 = check42(42) ^ error: Cannot prove that Int =:= 42. scala> def singleCheck42[T <: Singleton](x: T)(implicit ev: T =:= 42): T = x singleCheck42: [T <: Singleton](x: T)(implicit ev: T =:= 42)T scala> val x2 = singleCheck42(42) x2: Int = 42
- final case class Some[+A](value: A) extends Option[A] with Product with Serializable
Class
Some[A]
represents existing values of typeA
.Class
Some[A]
represents existing values of typeA
.- Annotations
- @SerialVersionUID()
- trait Specializable extends AnyRef
A common supertype for companions of specializable types.
A common supertype for companions of specializable types. Should not be extended in user code.
- type StringBuilder = scala.collection.mutable.StringBuilder
- case class StringContext(parts: String*) extends Product with Serializable
This class provides the basic mechanism to do String Interpolation.
This class provides the basic mechanism to do String Interpolation. String Interpolation allows users to embed variable references directly in *processed* string literals. Here's an example:
val name = "James" println(s"Hello, $name") // Hello, James
Any processed string literal is rewritten as an instantiation and method call against this class. For example:
s"Hello, $name"
is rewritten to be:
StringContext("Hello, ", "").s(name)
By default, this class provides the
raw
,s
andf
methods as available interpolators.To provide your own string interpolator, create an implicit class which adds a method to
StringContext
. Here's an example:implicit class JsonHelper(private val sc: StringContext) extends AnyVal { def json(args: Any*): JSONObject = ... } val x: JSONObject = json"{ a: $a }"
Here the
JsonHelper
extension class implicitly adds thejson
method toStringContext
which can be used forjson
string literals.- parts
The parts that make up the interpolated string, without the expressions that get inserted by interpolation.
- type StringIndexOutOfBoundsException = java.lang.StringIndexOutOfBoundsException
- final class Symbol extends Serializable
This class provides a simple way to get unique objects for equal strings.
This class provides a simple way to get unique objects for equal strings. Since symbols are interned, they can be compared using reference equality.
- type Throwable = java.lang.Throwable
- final case class Tuple1[+T1](_1: T1) extends Product1[T1] with Product with Serializable
A tuple of 1 elements; the canonical representation of a scala.Product1.
A tuple of 1 elements; the canonical representation of a scala.Product1.
- _1
Element 1 of this Tuple1
- final case class Tuple10[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10](_1: T1, _2: T2, _3: T3, _4: T4, _5: T5, _6: T6, _7: T7, _8: T8, _9: T9, _10: T10) extends Product10[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10] with Product with Serializable
A tuple of 10 elements; the canonical representation of a scala.Product10.
A tuple of 10 elements; the canonical representation of a scala.Product10.
- _1
Element 1 of this Tuple10
- _2
Element 2 of this Tuple10
- _3
Element 3 of this Tuple10
- _4
Element 4 of this Tuple10
- _5
Element 5 of this Tuple10
- _6
Element 6 of this Tuple10
- _7
Element 7 of this Tuple10
- _8
Element 8 of this Tuple10
- _9
Element 9 of this Tuple10
- _10
Element 10 of this Tuple10
- final case class Tuple11[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11](_1: T1, _2: T2, _3: T3, _4: T4, _5: T5, _6: T6, _7: T7, _8: T8, _9: T9, _10: T10, _11: T11) extends Product11[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11] with Product with Serializable
A tuple of 11 elements; the canonical representation of a scala.Product11.
A tuple of 11 elements; the canonical representation of a scala.Product11.
- _1
Element 1 of this Tuple11
- _2
Element 2 of this Tuple11
- _3
Element 3 of this Tuple11
- _4
Element 4 of this Tuple11
- _5
Element 5 of this Tuple11
- _6
Element 6 of this Tuple11
- _7
Element 7 of this Tuple11
- _8
Element 8 of this Tuple11
- _9
Element 9 of this Tuple11
- _10
Element 10 of this Tuple11
- _11
Element 11 of this Tuple11
- final case class Tuple12[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12](_1: T1, _2: T2, _3: T3, _4: T4, _5: T5, _6: T6, _7: T7, _8: T8, _9: T9, _10: T10, _11: T11, _12: T12) extends Product12[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12] with Product with Serializable
A tuple of 12 elements; the canonical representation of a scala.Product12.
A tuple of 12 elements; the canonical representation of a scala.Product12.
- _1
Element 1 of this Tuple12
- _2
Element 2 of this Tuple12
- _3
Element 3 of this Tuple12
- _4
Element 4 of this Tuple12
- _5
Element 5 of this Tuple12
- _6
Element 6 of this Tuple12
- _7
Element 7 of this Tuple12
- _8
Element 8 of this Tuple12
- _9
Element 9 of this Tuple12
- _10
Element 10 of this Tuple12
- _11
Element 11 of this Tuple12
- _12
Element 12 of this Tuple12
- final case class Tuple13[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13](_1: T1, _2: T2, _3: T3, _4: T4, _5: T5, _6: T6, _7: T7, _8: T8, _9: T9, _10: T10, _11: T11, _12: T12, _13: T13) extends Product13[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13] with Product with Serializable
A tuple of 13 elements; the canonical representation of a scala.Product13.
A tuple of 13 elements; the canonical representation of a scala.Product13.
- _1
Element 1 of this Tuple13
- _2
Element 2 of this Tuple13
- _3
Element 3 of this Tuple13
- _4
Element 4 of this Tuple13
- _5
Element 5 of this Tuple13
- _6
Element 6 of this Tuple13
- _7
Element 7 of this Tuple13
- _8
Element 8 of this Tuple13
- _9
Element 9 of this Tuple13
- _10
Element 10 of this Tuple13
- _11
Element 11 of this Tuple13
- _12
Element 12 of this Tuple13
- _13
Element 13 of this Tuple13
- final case class Tuple14[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14](_1: T1, _2: T2, _3: T3, _4: T4, _5: T5, _6: T6, _7: T7, _8: T8, _9: T9, _10: T10, _11: T11, _12: T12, _13: T13, _14: T14) extends Product14[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14] with Product with Serializable
A tuple of 14 elements; the canonical representation of a scala.Product14.
A tuple of 14 elements; the canonical representation of a scala.Product14.
- _1
Element 1 of this Tuple14
- _2
Element 2 of this Tuple14
- _3
Element 3 of this Tuple14
- _4
Element 4 of this Tuple14
- _5
Element 5 of this Tuple14
- _6
Element 6 of this Tuple14
- _7
Element 7 of this Tuple14
- _8
Element 8 of this Tuple14
- _9
Element 9 of this Tuple14
- _10
Element 10 of this Tuple14
- _11
Element 11 of this Tuple14
- _12
Element 12 of this Tuple14
- _13
Element 13 of this Tuple14
- _14
Element 14 of this Tuple14
- final case class Tuple15[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15](_1: T1, _2: T2, _3: T3, _4: T4, _5: T5, _6: T6, _7: T7, _8: T8, _9: T9, _10: T10, _11: T11, _12: T12, _13: T13, _14: T14, _15: T15) extends Product15[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15] with Product with Serializable
A tuple of 15 elements; the canonical representation of a scala.Product15.
A tuple of 15 elements; the canonical representation of a scala.Product15.
- _1
Element 1 of this Tuple15
- _2
Element 2 of this Tuple15
- _3
Element 3 of this Tuple15
- _4
Element 4 of this Tuple15
- _5
Element 5 of this Tuple15
- _6
Element 6 of this Tuple15
- _7
Element 7 of this Tuple15
- _8
Element 8 of this Tuple15
- _9
Element 9 of this Tuple15
- _10
Element 10 of this Tuple15
- _11
Element 11 of this Tuple15
- _12
Element 12 of this Tuple15
- _13
Element 13 of this Tuple15
- _14
Element 14 of this Tuple15
- _15
Element 15 of this Tuple15
- final case class Tuple16[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16](_1: T1, _2: T2, _3: T3, _4: T4, _5: T5, _6: T6, _7: T7, _8: T8, _9: T9, _10: T10, _11: T11, _12: T12, _13: T13, _14: T14, _15: T15, _16: T16) extends Product16[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16] with Product with Serializable
A tuple of 16 elements; the canonical representation of a scala.Product16.
A tuple of 16 elements; the canonical representation of a scala.Product16.
- _1
Element 1 of this Tuple16
- _2
Element 2 of this Tuple16
- _3
Element 3 of this Tuple16
- _4
Element 4 of this Tuple16
- _5
Element 5 of this Tuple16
- _6
Element 6 of this Tuple16
- _7
Element 7 of this Tuple16
- _8
Element 8 of this Tuple16
- _9
Element 9 of this Tuple16
- _10
Element 10 of this Tuple16
- _11
Element 11 of this Tuple16
- _12
Element 12 of this Tuple16
- _13
Element 13 of this Tuple16
- _14
Element 14 of this Tuple16
- _15
Element 15 of this Tuple16
- _16
Element 16 of this Tuple16
- final case class Tuple17[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17](_1: T1, _2: T2, _3: T3, _4: T4, _5: T5, _6: T6, _7: T7, _8: T8, _9: T9, _10: T10, _11: T11, _12: T12, _13: T13, _14: T14, _15: T15, _16: T16, _17: T17) extends Product17[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17] with Product with Serializable
A tuple of 17 elements; the canonical representation of a scala.Product17.
A tuple of 17 elements; the canonical representation of a scala.Product17.
- _1
Element 1 of this Tuple17
- _2
Element 2 of this Tuple17
- _3
Element 3 of this Tuple17
- _4
Element 4 of this Tuple17
- _5
Element 5 of this Tuple17
- _6
Element 6 of this Tuple17
- _7
Element 7 of this Tuple17
- _8
Element 8 of this Tuple17
- _9
Element 9 of this Tuple17
- _10
Element 10 of this Tuple17
- _11
Element 11 of this Tuple17
- _12
Element 12 of this Tuple17
- _13
Element 13 of this Tuple17
- _14
Element 14 of this Tuple17
- _15
Element 15 of this Tuple17
- _16
Element 16 of this Tuple17
- _17
Element 17 of this Tuple17
- final case class Tuple18[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17, +T18](_1: T1, _2: T2, _3: T3, _4: T4, _5: T5, _6: T6, _7: T7, _8: T8, _9: T9, _10: T10, _11: T11, _12: T12, _13: T13, _14: T14, _15: T15, _16: T16, _17: T17, _18: T18) extends Product18[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18] with Product with Serializable
A tuple of 18 elements; the canonical representation of a scala.Product18.
A tuple of 18 elements; the canonical representation of a scala.Product18.
- _1
Element 1 of this Tuple18
- _2
Element 2 of this Tuple18
- _3
Element 3 of this Tuple18
- _4
Element 4 of this Tuple18
- _5
Element 5 of this Tuple18
- _6
Element 6 of this Tuple18
- _7
Element 7 of this Tuple18
- _8
Element 8 of this Tuple18
- _9
Element 9 of this Tuple18
- _10
Element 10 of this Tuple18
- _11
Element 11 of this Tuple18
- _12
Element 12 of this Tuple18
- _13
Element 13 of this Tuple18
- _14
Element 14 of this Tuple18
- _15
Element 15 of this Tuple18
- _16
Element 16 of this Tuple18
- _17
Element 17 of this Tuple18
- _18
Element 18 of this Tuple18
- final case class Tuple19[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17, +T18, +T19](_1: T1, _2: T2, _3: T3, _4: T4, _5: T5, _6: T6, _7: T7, _8: T8, _9: T9, _10: T10, _11: T11, _12: T12, _13: T13, _14: T14, _15: T15, _16: T16, _17: T17, _18: T18, _19: T19) extends Product19[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19] with Product with Serializable
A tuple of 19 elements; the canonical representation of a scala.Product19.
A tuple of 19 elements; the canonical representation of a scala.Product19.
- _1
Element 1 of this Tuple19
- _2
Element 2 of this Tuple19
- _3
Element 3 of this Tuple19
- _4
Element 4 of this Tuple19
- _5
Element 5 of this Tuple19
- _6
Element 6 of this Tuple19
- _7
Element 7 of this Tuple19
- _8
Element 8 of this Tuple19
- _9
Element 9 of this Tuple19
- _10
Element 10 of this Tuple19
- _11
Element 11 of this Tuple19
- _12
Element 12 of this Tuple19
- _13
Element 13 of this Tuple19
- _14
Element 14 of this Tuple19
- _15
Element 15 of this Tuple19
- _16
Element 16 of this Tuple19
- _17
Element 17 of this Tuple19
- _18
Element 18 of this Tuple19
- _19
Element 19 of this Tuple19
- final case class Tuple2[+T1, +T2](_1: T1, _2: T2) extends Product2[T1, T2] with Product with Serializable
A tuple of 2 elements; the canonical representation of a scala.Product2.
A tuple of 2 elements; the canonical representation of a scala.Product2.
- _1
Element 1 of this Tuple2
- _2
Element 2 of this Tuple2
- final case class Tuple20[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17, +T18, +T19, +T20](_1: T1, _2: T2, _3: T3, _4: T4, _5: T5, _6: T6, _7: T7, _8: T8, _9: T9, _10: T10, _11: T11, _12: T12, _13: T13, _14: T14, _15: T15, _16: T16, _17: T17, _18: T18, _19: T19, _20: T20) extends Product20[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20] with Product with Serializable
A tuple of 20 elements; the canonical representation of a scala.Product20.
A tuple of 20 elements; the canonical representation of a scala.Product20.
- _1
Element 1 of this Tuple20
- _2
Element 2 of this Tuple20
- _3
Element 3 of this Tuple20
- _4
Element 4 of this Tuple20
- _5
Element 5 of this Tuple20
- _6
Element 6 of this Tuple20
- _7
Element 7 of this Tuple20
- _8
Element 8 of this Tuple20
- _9
Element 9 of this Tuple20
- _10
Element 10 of this Tuple20
- _11
Element 11 of this Tuple20
- _12
Element 12 of this Tuple20
- _13
Element 13 of this Tuple20
- _14
Element 14 of this Tuple20
- _15
Element 15 of this Tuple20
- _16
Element 16 of this Tuple20
- _17
Element 17 of this Tuple20
- _18
Element 18 of this Tuple20
- _19
Element 19 of this Tuple20
- _20
Element 20 of this Tuple20
- final case class Tuple21[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17, +T18, +T19, +T20, +T21](_1: T1, _2: T2, _3: T3, _4: T4, _5: T5, _6: T6, _7: T7, _8: T8, _9: T9, _10: T10, _11: T11, _12: T12, _13: T13, _14: T14, _15: T15, _16: T16, _17: T17, _18: T18, _19: T19, _20: T20, _21: T21) extends Product21[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21] with Product with Serializable
A tuple of 21 elements; the canonical representation of a scala.Product21.
A tuple of 21 elements; the canonical representation of a scala.Product21.
- _1
Element 1 of this Tuple21
- _2
Element 2 of this Tuple21
- _3
Element 3 of this Tuple21
- _4
Element 4 of this Tuple21
- _5
Element 5 of this Tuple21
- _6
Element 6 of this Tuple21
- _7
Element 7 of this Tuple21
- _8
Element 8 of this Tuple21
- _9
Element 9 of this Tuple21
- _10
Element 10 of this Tuple21
- _11
Element 11 of this Tuple21
- _12
Element 12 of this Tuple21
- _13
Element 13 of this Tuple21
- _14
Element 14 of this Tuple21
- _15
Element 15 of this Tuple21
- _16
Element 16 of this Tuple21
- _17
Element 17 of this Tuple21
- _18
Element 18 of this Tuple21
- _19
Element 19 of this Tuple21
- _20
Element 20 of this Tuple21
- _21
Element 21 of this Tuple21
- final case class Tuple22[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17, +T18, +T19, +T20, +T21, +T22](_1: T1, _2: T2, _3: T3, _4: T4, _5: T5, _6: T6, _7: T7, _8: T8, _9: T9, _10: T10, _11: T11, _12: T12, _13: T13, _14: T14, _15: T15, _16: T16, _17: T17, _18: T18, _19: T19, _20: T20, _21: T21, _22: T22) extends Product22[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22] with Product with Serializable
A tuple of 22 elements; the canonical representation of a scala.Product22.
A tuple of 22 elements; the canonical representation of a scala.Product22.
- _1
Element 1 of this Tuple22
- _2
Element 2 of this Tuple22
- _3
Element 3 of this Tuple22
- _4
Element 4 of this Tuple22
- _5
Element 5 of this Tuple22
- _6
Element 6 of this Tuple22
- _7
Element 7 of this Tuple22
- _8
Element 8 of this Tuple22
- _9
Element 9 of this Tuple22
- _10
Element 10 of this Tuple22
- _11
Element 11 of this Tuple22
- _12
Element 12 of this Tuple22
- _13
Element 13 of this Tuple22
- _14
Element 14 of this Tuple22
- _15
Element 15 of this Tuple22
- _16
Element 16 of this Tuple22
- _17
Element 17 of this Tuple22
- _18
Element 18 of this Tuple22
- _19
Element 19 of this Tuple22
- _20
Element 20 of this Tuple22
- _21
Element 21 of this Tuple22
- _22
Element 22 of this Tuple22
- final case class Tuple3[+T1, +T2, +T3](_1: T1, _2: T2, _3: T3) extends Product3[T1, T2, T3] with Product with Serializable
A tuple of 3 elements; the canonical representation of a scala.Product3.
A tuple of 3 elements; the canonical representation of a scala.Product3.
- _1
Element 1 of this Tuple3
- _2
Element 2 of this Tuple3
- _3
Element 3 of this Tuple3
- final case class Tuple4[+T1, +T2, +T3, +T4](_1: T1, _2: T2, _3: T3, _4: T4) extends Product4[T1, T2, T3, T4] with Product with Serializable
A tuple of 4 elements; the canonical representation of a scala.Product4.
A tuple of 4 elements; the canonical representation of a scala.Product4.
- _1
Element 1 of this Tuple4
- _2
Element 2 of this Tuple4
- _3
Element 3 of this Tuple4
- _4
Element 4 of this Tuple4
- final case class Tuple5[+T1, +T2, +T3, +T4, +T5](_1: T1, _2: T2, _3: T3, _4: T4, _5: T5) extends Product5[T1, T2, T3, T4, T5] with Product with Serializable
A tuple of 5 elements; the canonical representation of a scala.Product5.
A tuple of 5 elements; the canonical representation of a scala.Product5.
- _1
Element 1 of this Tuple5
- _2
Element 2 of this Tuple5
- _3
Element 3 of this Tuple5
- _4
Element 4 of this Tuple5
- _5
Element 5 of this Tuple5
- final case class Tuple6[+T1, +T2, +T3, +T4, +T5, +T6](_1: T1, _2: T2, _3: T3, _4: T4, _5: T5, _6: T6) extends Product6[T1, T2, T3, T4, T5, T6] with Product with Serializable
A tuple of 6 elements; the canonical representation of a scala.Product6.
A tuple of 6 elements; the canonical representation of a scala.Product6.
- _1
Element 1 of this Tuple6
- _2
Element 2 of this Tuple6
- _3
Element 3 of this Tuple6
- _4
Element 4 of this Tuple6
- _5
Element 5 of this Tuple6
- _6
Element 6 of this Tuple6
- final case class Tuple7[+T1, +T2, +T3, +T4, +T5, +T6, +T7](_1: T1, _2: T2, _3: T3, _4: T4, _5: T5, _6: T6, _7: T7) extends Product7[T1, T2, T3, T4, T5, T6, T7] with Product with Serializable
A tuple of 7 elements; the canonical representation of a scala.Product7.
A tuple of 7 elements; the canonical representation of a scala.Product7.
- _1
Element 1 of this Tuple7
- _2
Element 2 of this Tuple7
- _3
Element 3 of this Tuple7
- _4
Element 4 of this Tuple7
- _5
Element 5 of this Tuple7
- _6
Element 6 of this Tuple7
- _7
Element 7 of this Tuple7
- final case class Tuple8[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8](_1: T1, _2: T2, _3: T3, _4: T4, _5: T5, _6: T6, _7: T7, _8: T8) extends Product8[T1, T2, T3, T4, T5, T6, T7, T8] with Product with Serializable
A tuple of 8 elements; the canonical representation of a scala.Product8.
A tuple of 8 elements; the canonical representation of a scala.Product8.
- _1
Element 1 of this Tuple8
- _2
Element 2 of this Tuple8
- _3
Element 3 of this Tuple8
- _4
Element 4 of this Tuple8
- _5
Element 5 of this Tuple8
- _6
Element 6 of this Tuple8
- _7
Element 7 of this Tuple8
- _8
Element 8 of this Tuple8
- final case class Tuple9[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9](_1: T1, _2: T2, _3: T3, _4: T4, _5: T5, _6: T6, _7: T7, _8: T8, _9: T9) extends Product9[T1, T2, T3, T4, T5, T6, T7, T8, T9] with Product with Serializable
A tuple of 9 elements; the canonical representation of a scala.Product9.
A tuple of 9 elements; the canonical representation of a scala.Product9.
- _1
Element 1 of this Tuple9
- _2
Element 2 of this Tuple9
- _3
Element 3 of this Tuple9
- _4
Element 4 of this Tuple9
- _5
Element 5 of this Tuple9
- _6
Element 6 of this Tuple9
- _7
Element 7 of this Tuple9
- _8
Element 8 of this Tuple9
- _9
Element 9 of this Tuple9
- final case class UninitializedFieldError(msg: String) extends RuntimeException with Product with Serializable
This class implements errors which are thrown whenever a field is used before it has been initialized.
This class implements errors which are thrown whenever a field is used before it has been initialized.
Such runtime checks are not emitted by default. They can be enabled by the
-Xcheckinit
compiler option. - abstract final class Unit extends AnyVal
Unit
is a subtype of scala.AnyVal.Unit
is a subtype of scala.AnyVal. There is only one value of typeUnit
,()
, and it is not represented by any object in the underlying runtime system. A method with return typeUnit
is analogous to a Java method which is declaredvoid
. - type UnsupportedOperationException = java.lang.UnsupportedOperationException
- final class ValueOf[T] extends AnyVal
ValueOf[T]
provides the unique value of the typeT
whereT
is a type which has a single inhabitant.ValueOf[T]
provides the unique value of the typeT
whereT
is a type which has a single inhabitant. Eligible types are singleton types of the formstablePath.type
, Unit and singleton types corresponding to value literals.The value itself can conveniently be retrieved with Predef#valueOf, which requires a
ValueOf
to be available in implicit scope.The compiler provides instances of
ValueOf[T]
for all eligible types. Typically an instance would be required where a runtime value corresponding to a type level computation is needed.For example, we might define a type
Residue[M <: Int]
corresponding to the group of integers moduloM
. We could then mandate that residues can be summed only when they are parameterized by the same modulus,case class Residue[M <: Int](n: Int) extends AnyVal { def +(rhs: Residue[M])(implicit m: ValueOf[M]): Residue[M] = Residue((this.n + rhs.n) % valueOf[M]) } val fiveModTen = Residue[10](5) val nineModTen = Residue[10](9) fiveModTen + nineModTen // OK == Residue[10](4) val fourModEleven = Residue[11](4) fiveModTen + fourModEleven // compiler error: type mismatch; // found : Residue[11] // required: Residue[10]
Notice that here the modulus is encoded in the type of the values and so does not incur any additional per-value storage cost. When a runtime value of the modulus is required in the implementation of
+
it is provided at the call site via the implicit argumentm
of typeValueOf[M]
.- Annotations
- @implicitNotFound()
- type Vector[+A] = scala.collection.immutable.Vector[A]
- class deprecated extends Annotation with ConstantAnnotation
An annotation that designates that a definition is deprecated.
An annotation that designates that a definition is deprecated. A deprecation warning is issued upon usage of the annotated definition.
Library authors should state the library's deprecation policy in their documentation to give developers guidance on how long a deprecated definition will be preserved.
Library authors should prepend the name of their library to the version number to help developers distinguish deprecations coming from different libraries:
@deprecated("this method will be removed", "FooLib 12.0") def oldMethod(x: Int) = ...
The compiler will emit deprecation warnings grouped by library and version:
oldMethod(1) oldMethod(2) aDeprecatedMethodFromLibraryBar(3, 4) // warning: there was one deprecation warning (since BarLib 3.2) // warning: there were two deprecation warnings (since FooLib 12.0) // warning: there were three deprecation warnings in total; re-run with -deprecation for details
The Scala compiler also warns about using definitions annotated with java.lang.Deprecated. However it is recommended to use the Scala
@deprecated
annotation in Scala code because it allows providing a deprecation message.@deprecated
in the Scala language and its standard libraryA deprecated element of the Scala language or a definition in the Scala standard library will be preserved at least for the current major version.
This means that an element deprecated in some 2.13.x release will be preserved in all 2.13.x releases, but may be removed in the future. (A deprecated element might be kept longer to ease migration, but developers should not rely on this.)
- Annotations
- @getter() @setter() @beanGetter() @beanSetter() @field() @deprecatedInheritance()
- See also
The official documentation on binary compatibility.
- final class deprecatedInheritance extends Annotation with ConstantAnnotation
An annotation that designates that inheriting from a class is deprecated.
An annotation that designates that inheriting from a class is deprecated.
This is usually done to warn about a non-final class being made final in a future version. Sub-classing such a class then generates a warning.
No warnings are generated if the subclass is in the same compilation unit.
Library authors should state the library's deprecation policy in their documentation to give developers guidance on when a type annotated with
@deprecatedInheritance
will befinal
ized.Library authors should prepend the name of their library to the version number to help developers distinguish deprecations coming from different libraries:
@deprecatedInheritance("this class will be made final", "FooLib 12.0") class Foo
val foo = new Foo // no deprecation warning class Bar extends Foo // warning: inheritance from class Foo is deprecated (since FooLib 12.0): this class will be made final // class Bar extends Foo // ^
- Annotations
- @getter() @setter() @beanGetter() @beanSetter()
- See also
- class deprecatedName extends Annotation with StaticAnnotation
An annotation that designates that the name of a parameter is deprecated.
An annotation that designates that the name of a parameter is deprecated.
Using this name in a named argument generates a deprecation warning.
If the
name
is omitted, then using the canonical name is deprecated. In that case, lints such as-Xlint:named-booleans
which encourage the use of a name will not warn.Library authors should state the library's deprecation policy in their documentation to give developers guidance on how long a deprecated name will be preserved.
Library authors should prepend the name of their library to the version number to help developers distinguish deprecations coming from different libraries:
def inc(x: Int, @deprecatedName("y", "FooLib 12.0") n: Int): Int = x + n inc(1, y = 2)
will produce the following warning:
warning: the parameter name y is deprecated (since FooLib 12.0): use n instead inc(1, y = 2) ^
- Annotations
- @param() @deprecatedInheritance()
- See also
- class deprecatedOverriding extends Annotation with ConstantAnnotation
An annotation that designates that overriding a member is deprecated.
An annotation that designates that overriding a member is deprecated.
Overriding such a member in a sub-class then generates a warning.
Library authors should state the library's deprecation policy in their documentation to give developers guidance on when a method annotated with
@deprecatedOverriding
will befinal
ized.Library authors should prepend the name of their library to the version number to help developers distinguish deprecations coming from different libraries:
class Foo { @deprecatedOverriding("this method will be made final", "FooLib 12.0") def add(x: Int, y: Int) = x + y }
class Bar extends Foo // no deprecation warning class Baz extends Foo { override def add(x: Int, y: Int) = x - y } // warning: overriding method add in class Foo is deprecated (since FooLib 12.0): this method will be made final // override def add(x: Int, y: Int) = x - y // ^
- Annotations
- @getter() @setter() @beanGetter() @beanSetter() @deprecatedInheritance()
- See also
- class inline extends Annotation with StaticAnnotation
An annotation for methods that the optimizer should inline.
An annotation for methods that the optimizer should inline.
Note that by default, the Scala optimizer is disabled and no callsites are inlined. See
-opt:help
and the overview document for information on how to enable the optimizer and inliner.When inlining is enabled, the inliner will always try to inline methods or callsites annotated
@inline
(under the condition that inlining from the defining class is allowed). If inlining is not possible, for example because the method is not final, an optimizer warning will be issued. See-Wopt:help
for details.Examples:
@inline final def f1(x: Int) = x @noinline final def f2(x: Int) = x final def f3(x: Int) = x def t1 = f1(1) // inlined if possible def t2 = f2(1) // not inlined def t3 = f3(1) // may be inlined (the inliner heuristics can select the callsite) def t4 = f1(1): @noinline // not inlined (override at callsite) def t5 = f2(1): @inline // inlined if possible (override at callsite) def t6 = f3(1): @inline // inlined if possible def t7 = f3(1): @noinline // not inlined }
Note: parentheses are required when annotating a callsite within a larger expression.
def t1 = f1(1) + f1(1): @noinline // equivalent to (f1(1) + f1(1)): @noinline def t2 = f1(1) + (f1(1): @noinline) // the second call to f1 is not inlined
- Annotations
- @deprecatedInheritance()
- class native extends Annotation with StaticAnnotation
Marker for native methods.
Marker for native methods.
@native def f(x: Int, y: List[Long]): String = ...
A
@native
method is compiled to the platform's native method, while discarding the method's body (if any). The body will be type checked if present.A method marked @native must be a member of a class, not a trait (since 2.12).
- Annotations
- @deprecatedInheritance()
- final class noinline extends Annotation with StaticAnnotation
An annotation for methods that the optimizer should not inline.
An annotation for methods that the optimizer should not inline.
Note that by default, the Scala optimizer is disabled and no callsites are inlined. See
-opt:help
for information how to enable the optimizer and inliner.When inlining is enabled, the inliner will never inline methods or callsites annotated
@noinline
.Examples:
@inline final def f1(x: Int) = x @noinline final def f2(x: Int) = x final def f3(x: Int) = x def t1 = f1(1) // inlined if possible def t2 = f2(1) // not inlined def t3 = f3(1) // may be inlined (the inliner heuristics can select the callsite) def t4 = f1(1): @noinline // not inlined (override at callsite) def t5 = f2(1): @inline // inlined if possible (override at callsite) def t6 = f3(1): @inline // inlined if possible def t7 = f3(1): @noinline // not inlined }
Note: parentheses are required when annotating a callsite within a larger expression.
def t1 = f1(1) + f1(1): @noinline // equivalent to (f1(1) + f1(1)): @noinline def t2 = f1(1) + (f1(1): @noinline) // the second call to f1 is not inlined
- final class specialized extends Annotation with StaticAnnotation
Annotate type parameters on which code should be automatically specialized.
Annotate type parameters on which code should be automatically specialized. For example:
class MyList[@specialized T] ...
Type T can be specialized on a subset of the primitive types by specifying a list of primitive types to specialize at:
class MyList[@specialized(Int, Double, Boolean) T] ..
- final class throws[T <: Throwable] extends Annotation with StaticAnnotation
Annotation for specifying the exceptions thrown by a method.
Annotation for specifying the exceptions thrown by a method. For example:
class Reader(fname: String) { private val in = new BufferedReader(new FileReader(fname)) @throws[IOException]("if the file doesn't exist") def read() = in.read() }
- final class transient extends Annotation with StaticAnnotation
- Annotations
- @field()
- final class unchecked extends Annotation
An annotation to designate that the annotated entity should not be considered for additional compiler checks.
An annotation to designate that the annotated entity should not be considered for additional compiler checks. Specific applications include annotating the subject of a match expression to suppress exhaustiveness and reachability warnings, and annotating a type argument in a match case to suppress unchecked warnings.
Such suppression should be used with caution, without which one may encounter scala.MatchError or java.lang.ClassCastException at runtime. In most cases one can and should address the warning instead of suppressing it.
object Test extends App { // This would normally warn "match is not exhaustive" // because `None` is not covered. def f(x: Option[String]) = (x: @unchecked) match { case Some(y) => y } // This would normally warn "type pattern is unchecked" // but here will blindly cast the head element to String. def g(xs: Any) = xs match { case x: List[String @unchecked] => x.head } }
- final class volatile extends Annotation with StaticAnnotation
- Annotations
- @field()
Deprecated Type Members
- type BufferedIterator[+A] = scala.collection.BufferedIterator[A]
- Annotations
- @deprecated
- Deprecated
(Since version 2.13.0) Use scala.collection.BufferedIterator instead of scala.BufferedIterator
- trait DelayedInit extends AnyRef
Classes and objects (but note, not traits) inheriting the
DelayedInit
marker trait will have their initialization code rewritten as follows:code
becomesdelayedInit(code)
.Classes and objects (but note, not traits) inheriting the
DelayedInit
marker trait will have their initialization code rewritten as follows:code
becomesdelayedInit(code)
.Initialization code comprises all statements and all value definitions that are executed during initialization.
Example:
trait Helper extends DelayedInit { def delayedInit(body: => Unit) = { println("dummy text, printed before initialization of C") body // evaluates the initialization code of C } } class C extends Helper { println("this is the initialization code of C") } object Test extends App { val c = new C }
Should result in the following being printed:
dummy text, printed before initialization of C this is the initialization code of C
- Annotations
- @deprecated
- Deprecated
(Since version 2.11.0) DelayedInit semantics can be surprising. Support for
App
will continue. See the release notes for more details: https://github.com/scala/scala/releases/tag/v2.11.0- See also
"Delayed Initialization" subsection of the Scala Language Specification (section 5.1)
- trait Proxy extends Any
This class implements a simple proxy that forwards all calls to the public, non-final methods defined in class
Any
to another object self.This class implements a simple proxy that forwards all calls to the public, non-final methods defined in class
Any
to another object self. Those methods are:def hashCode(): Int def equals(other: Any): Boolean def toString(): String
Note: forwarding methods in this way will most likely create an asymmetric equals method, which is not generally recommended.
- Annotations
- @deprecated
- Deprecated
(Since version 2.13.0) Explicitly override hashCode, equals and toString instead.
- type Stream[+A] = scala.collection.immutable.Stream[A]
- Annotations
- @deprecated
- Deprecated
(Since version 2.13.0) Use LazyList instead of Stream
- type Traversable[+A] = scala.collection.Iterable[A]
- Annotations
- @deprecated
- Deprecated
(Since version 2.13.0) Use Iterable instead of Traversable
- type TraversableOnce[+A] = scala.collection.IterableOnce[A]
- Annotations
- @deprecated
- Deprecated
(Since version 2.13.0) Use IterableOnce instead of TraversableOnce
- final class UninitializedError extends RuntimeException
This class represents uninitialized variable/value errors.
This class represents uninitialized variable/value errors.
- Annotations
- @deprecated
- Deprecated
(Since version 2.12.7) will be removed in a future release
Value Members
- val +:: scala.collection.+:.type
- val :+: scala.collection.:+.type
- val ::: scala.collection.immutable.::.type
- val AnyRef: Specializable
- val BigDecimal: scala.math.BigDecimal.type
- val BigInt: scala.math.BigInt.type
- val Either: scala.util.Either.type
- val Equiv: scala.math.Equiv.type
- val Fractional: scala.math.Fractional.type
- val IndexedSeq: scala.collection.immutable.IndexedSeq.type
- val Integral: scala.math.Integral.type
- val Iterable: scala.collection.Iterable.type
- val Iterator: scala.collection.Iterator.type
- val LazyList: scala.collection.immutable.LazyList.type
- val Left: scala.util.Left.type
- val List: scala.collection.immutable.List.type
- val Nil: scala.collection.immutable.Nil.type
- val Numeric: scala.math.Numeric.type
- val Ordered: scala.math.Ordered.type
- val Ordering: scala.math.Ordering.type
- val Range: scala.collection.immutable.Range.type
- val Right: scala.util.Right.type
- val Seq: scala.collection.immutable.Seq.type
- val StringBuilder: scala.collection.mutable.StringBuilder.type
- val Vector: scala.collection.immutable.Vector.type
- object #::
- object <:< extends java.io.Serializable
- object Array extends java.io.Serializable
Utility methods for operating on arrays.
Utility methods for operating on arrays. For example:
val a = Array(1, 2) val b = Array.ofDim[Int](2) val c = Array.concat(a, b)
where the array objects
a
,b
andc
have respectively the valuesArray(1, 2)
,Array(0, 0)
andArray(1, 2, 0, 0)
. - object Boolean extends AnyValCompanion
- object Byte extends AnyValCompanion
- object Char extends AnyValCompanion
- object Console extends AnsiColor
Implements functionality for printing Scala values on the terminal.
Implements functionality for printing Scala values on the terminal. For reading values use StdIn. Also defines constants for marking up text on ANSI terminals.
Console Output
Use the print methods to output text.
scala> Console.printf( "Today the outside temperature is a balmy %.1f°C. %<.1f°C beats the previous record of %.1f°C.\n", -137.0, -135.05) Today the outside temperature is a balmy -137.0°C. -137.0°C beats the previous record of -135.1°C.
ANSI escape codes
Use the ANSI escape codes for colorizing console output either to STDOUT or STDERR.
import Console.{GREEN, RED, RESET, YELLOW_B, UNDERLINED} object PrimeTest { def isPrime(): Unit = { val candidate = io.StdIn.readInt().ensuring(_ > 1) val prime = (2 to candidate - 1).forall(candidate % _ != 0) if (prime) Console.println(s"${RESET}${GREEN}yes${RESET}") else Console.err.println(s"${RESET}${YELLOW_B}${RED}${UNDERLINED}NO!${RESET}") } def main(args: Array[String]): Unit = isPrime() }
$ scala PrimeTest 1234567891 yes $ scala PrimeTest 56474 NO! IO redefinition
Use IO redefinition to temporarily swap in a different set of input and/or output streams. In this example the stream based method above is wrapped into a function.
import java.io.{ByteArrayOutputStream, StringReader} object FunctionalPrimeTest { def isPrime(candidate: Int): Boolean = { val input = new StringReader(s"$candidate\n") val outCapture = new ByteArrayOutputStream val errCapture = new ByteArrayOutputStream Console.withIn(input) { Console.withOut(outCapture) { Console.withErr(errCapture) { PrimeTest.isPrime() } } } if (outCapture.toByteArray.nonEmpty) // "yes" true else if (errCapture.toByteArray.nonEmpty) // "NO!" false else throw new IllegalArgumentException(candidate.toString) } def main(args: Array[String]): Unit = { val primes = (2 to 50) filter (isPrime) println(s"First primes: $primes") } }
$ scala FunctionalPrimeTest First primes: Vector(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47) - object Double extends AnyValCompanion
- object DummyImplicit
- object Float extends AnyValCompanion
- object Function
A module defining utility methods for higher-order functional programming.
- object Function1
- object Int extends AnyValCompanion
- object Long extends AnyValCompanion
- case object None extends Option[Nothing] with Product with Serializable
This case object represents non-existent values.
This case object represents non-existent values.
- Annotations
- @SerialVersionUID()
- object Option extends java.io.Serializable
- object PartialFunction
A few handy operations which leverage the extra bit of information available in partial functions.
A few handy operations which leverage the extra bit of information available in partial functions. Examples:
import PartialFunction._ def strangeConditional(other: Any): Boolean = cond(other) { case x: String if x == "abc" || x == "def" => true case x: Int => true } def onlyInt(v: Any): Option[Int] = condOpt(v) { case x: Int => x }
- object Predef extends LowPriorityImplicits
The
Predef
object provides definitions that are accessible in all Scala compilation units without explicit qualification.The
Predef
object provides definitions that are accessible in all Scala compilation units without explicit qualification.Commonly Used Types
Predef provides type aliases for types which are commonly used, such as the immutable collection types scala.collection.immutable.Map and scala.collection.immutable.Set.
Console Output
For basic console output,
Predef
provides convenience methods print and println, which are aliases of the methods in the object scala.Console.Assertions
A set of
assert
functions are provided for use as a way to document and dynamically check invariants in code. Invocations ofassert
can be elided at compile time by providing the command line option-Xdisable-assertions
, which raises-Xelide-below
aboveelidable.ASSERTION
, to thescalac
command.Variants of
assert
intended for use with static analysis tools are also provided:assume
,require
andensuring
.require
andensuring
are intended for use as a means of design-by-contract style specification of pre- and post-conditions on functions, with the intention that these specifications could be consumed by a static analysis tool. For instance,def addNaturals(nats: List[Int]): Int = { require(nats forall (_ >= 0), "List contains negative numbers") nats.foldLeft(0)(_ + _) } ensuring(_ >= 0)
The declaration of
addNaturals
states that the list of integers passed should only contain natural numbers (i.e. non-negative), and that the result returned will also be natural.require
is distinct fromassert
in that if the condition fails, then the caller of the function is to blame rather than a logical error having been made withinaddNaturals
itself.ensuring
is a form ofassert
that declares the guarantee the function is providing with regards to its return value.Implicit Conversions
A number of commonly applied implicit conversions are also defined here, and in the parent type scala.LowPriorityImplicits. Implicit conversions are provided for the "widening" of numeric values, for instance, converting a Short value to a Long value as required, and to add additional higher-order functions to Array values. These are described in more detail in the documentation of scala.Array.
- object Product1
- object Product10
- object Product11
- object Product12
- object Product13
- object Product14
- object Product15
- object Product16
- object Product17
- object Product18
- object Product19
- object Product2
- object Product20
- object Product21
- object Product22
- object Product3
- object Product4
- object Product5
- object Product6
- object Product7
- object Product8
- object Product9
- object Short extends AnyValCompanion
- object Specializable
- object StringContext extends java.io.Serializable
- object Symbol extends UniquenessCache[String, Symbol] with java.io.Serializable
- object Unit extends AnyValCompanion
- Annotations
- @compileTimeOnly(message = "`Unit` companion object is not allowed in source; instead, use `()` for the unit value")
- object language
The
scala.language
object controls the language features available to the programmer, as proposed in the SIP-18 document.The
scala.language
object controls the language features available to the programmer, as proposed in the SIP-18 document.Each of these features has to be explicitly imported into the current scope to become available:
import language.postfixOps // or language._ List(1, 2, 3) reverse
The language features are:
dynamics
enables defining calls rewriting using theDynamic
traitexistentials
enables writing existential typeshigherKinds
enables writing higher-kinded typesimplicitConversions
enables defining implicit methods and memberspostfixOps
enables postfix operators (not recommended)reflectiveCalls
enables using structural typesexperimental
contains newer features that have not yet been tested in production
- object languageFeature
Deprecated Value Members
- val Stream: scala.collection.immutable.Stream.type
- Annotations
- @deprecated
- Deprecated
(Since version 2.13.0) Use LazyList instead of Stream
- val Traversable: scala.collection.Iterable.type
- Annotations
- @deprecated
- Deprecated
(Since version 2.13.0) Use Iterable instead of Traversable
- object Proxy
- Annotations
- @deprecated
- Deprecated
(Since version 2.13.0) All members of this object are deprecated.
This is the documentation for the Scala standard library.
Package structure
The scala package contains core types like
Int
,Float
,Array
orOption
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 frameworkscala.collection.immutable
- Immutable, sequential data-structures such asVector
,List
,Range
,HashMap
orHashSet
scala.collection.mutable
- Mutable, sequential data-structures such asArrayBuffer
,StringBuilder
,HashMap
orHashSet
scala.collection.concurrent
- Mutable, concurrent data-structures such asTrieMap
scala.concurrent
- Primitives for concurrent programming such asFutures
andPromises
scala.io
- Input and output operationsscala.math
- Basic math functions and additional numeric types likeBigInt
andBigDecimal
scala.sys
- Interaction with other processes and the operating systemscala.util.matching
- Regular expressionsOther 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.collection.parallel
- Parallel collections (scala-parallel-collections.jar)scala.util.parsing
- Parser combinators (scala-parser-combinators.jar)scala.swing
- A convenient wrapper around Java's GUI framework called Swing (scala-swing.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 forscala.collection.immutable.List
.Other aliases refer to classes provided by the underlying platform. For example, on the JVM,
String
is an alias forjava.lang.String
.