On this page
Package scala.scala
package scala
Core Scala types. They are always available without an explicit import.
Classlikes
Source
object #::
Source@showAsInfix
Companion | object |
---|
Source
object *:
Companion | class |
---|
Source@implicitNotFound(msg = "Cannot prove that ${From} <:>
sealed abstract class <:<[-From, +To] extends From => To with Serializable
An instance of A <:< B
witnesses that A
is a subtype of B
. Requiring an implicit argument of the type A <:< B
encodes the generalized constraint A <: 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 type T <:< U
, where U
is the required upper bound; or for lower-bounds, use: L <:< T
, where L
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 a To
, and substituteContra replaces the To
s in a type with From
s.
In part contributed by Jason Zaugg.
Type parameters |
|
---|---|
See also | =:= for expressing equality constraints |
Example |
|
Companion | object |
Source
object <:<
Companion | class |
---|
Source@implicitNotFound(msg = "Cannot prove that ${From} =:= ${To}.")
An instance of A =:= B
witnesses that the types A
and B
are equal. It also acts as a A <:< B
, but not a B <:< 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 a To
, and substituteContra replaces the To
s in a type with From
s.
Type parameters |
|
---|---|
See also | <:< for expressing subtyping constraints |
Example | An in-place variant of scala.collection.mutable.ArrayBuffer#transpose
|
abstract open class Any
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 extends Any
, only has def
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.
final abstract class AnyKind
The super-type of all types.
See https://dotty.epfl.ch/docs/reference/other-new-features/kind-polymorphism.html.
class AnyRef
Class AnyRef
is the root class of all reference types. All types except the value types descend from this class.
abstract open class AnyVal
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 of AnyVal
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 nestedtraits
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.
Source@nowarn("cat=deprecation&origin=scala\\.DelayedInit")
trait App extends DelayedInit
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
.
Source
object Array
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
and c
have respectively the values Array(1, 2)
, Array(0, 0)
and Array(1, 2, 0, 0)
.
Companion | class |
---|
Source
Arrays are mutable, indexed collections of values. Array[T]
is Scala's representation for Java's T[]
.
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 to update(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 on ArrayOps
return an Array
, while the conversion to ArraySeq
is permanent as all operations return a ArraySeq
.
The conversion to ArrayOps
takes priority over the conversion to ArraySeq
. 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 type Array[Int]
, with an implicit conversion to ArrayOps
occurring to perform the reverse
operation. The value of seqReversed
, on the other hand, will be computed by converting to ArraySeq
first and invoking the variant of reverse
that returns another ArraySeq
.
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 |
---|---|
Companion | object |
Source
Boolean
(equivalent to Java's boolean
primitive type) is a subtype of scala.AnyVal. Instances of Boolean
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.
Companion | object |
---|
Source
object Boolean
Companion | class |
---|
Source
Byte
, a 8-bit signed integer (equivalent to Java's byte
primitive type) is a subtype of scala.AnyVal. Instances of Byte
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.
Companion | object |
---|
Source
object Byte
Companion | class |
---|
Source@implicitNotFound("Values of types ${L} and ${R} cannot be compared with == or !=")
sealed trait CanEqual[-L, -R]
A marker trait indicating that values of type L
can be compared to values of type R
.
Companion | object |
---|
Source
object CanEqual
Companion object containing a few universally known CanEqual
instances. CanEqual instances involving primitive types or the Null type are handled directly in the compiler (see Implicits.synthesizedCanEqual), so they are not included here.
Companion | class |
---|
Source@experimental @implicitNotFound("The capability to throw exception ${E} is missing.\nThe capability can be provided by one of the following:\n - Adding a using clause `(using CanThrow[${E}])` to the definition of the enclosing method\n - Adding `throws ${E}` clause after the result type of the enclosing method\n - Wrapping this piece of code with a `try` block that catches ${E}")
A capability class that allows to throw exception E
. When used with the experimental.saferExceptions feature, a throw Ex()
expression will require a given of class CanThrow[Ex]
to be available.
Source
Char
, a 16-bit unsigned integer (equivalent to Java's char
primitive type) is a subtype of scala.AnyVal. Instances of Char
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.
Companion | object |
---|
Source
object Char
Companion | class |
---|
Source
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) |
Source@FunctionalInterface
abstract class Conversion[-T, +U] extends T => U
A class for implicit values that can serve as implicit conversions The implicit resolution algorithm will act as if there existed the additional implicit definition:
def $implicitConversion[T, U](x: T)(c: Conversion[T, U]): U = c(x)
However, the presence of this definition would slow down implicit search since its outermost type matches any pair of types. Therefore, implicit search contains a special case in Implicits#discardForView
which emulates the conversion in a more efficient way.
Note that this is a SAM class - function literals are automatically converted to the Conversion
values.
Also note that in bootstrapped dotty, Predef.<:<
should inherit from Conversion
. This would cut the number of special cases in discardForView
from two to one.
The Conversion
class can also be used to convert explicitly, using the convert
extension method.
Source
Double
, a 64-bit IEEE-754 floating point number (equivalent to Java's double
primitive type) is a subtype of scala.AnyVal. Instances of Double
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.
Companion | object |
---|
Source
object Double
Companion | class |
---|
Source
final class DummyImplicit
A type for which there is always an implicit value.
Companion | object |
---|
Source
object DummyImplicit
Companion | class |
---|
Source
trait Dynamic
A marker trait that enables dynamic invocations. Instances x
of this trait allow method invocations x.meth(args)
for arbitrary method names meth
and argument lists args
as well as field accesses x.field
for arbitrary field names field
.
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.
Source
object EmptyTuple extends Tuple
A tuple of 0 elements.
Source@SerialVersionUID(8476000850333817230L)
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 as val
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.
Value parameters |
|
---|---|
Example |
|
Source
trait Equals
An interface containing operations for equality. The only method not already present in class AnyRef
is canEqual
.
Source
Float
, a 32-bit IEEE-754 floating point number (equivalent to Java's float
primitive type) is a subtype of scala.AnyVal. Instances of Float
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.
Companion | object |
---|
Source
object Float
Companion | class |
---|
Source
object Function
A module defining utility methods for higher-order functional programming.
Source
A function of 0 parameters.
In the following example, the definition of javaVersion is a shorthand for the anonymous class definition anonfun0:
object Main extends App {
val javaVersion = () => sys.props("java.version")
val anonfun0 = new Function0[String] {
def apply(): String = sys.props("java.version")
}
assert(javaVersion() == anonfun0())
}
Source
object Function1
Companion | class |
---|
Source@implicitNotFound(msg = "No implicit view available from ${T1} => ${R}.")
A function of 1 parameter.
In the following example, the definition of succ is a shorthand for the anonymous class definition anonfun1:
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.
Companion | object |
---|
Source
trait Function10[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, +R] extends AnyRef
A function of 10 parameters.
Source
trait Function11[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, +R] extends AnyRef
A function of 11 parameters.
Source
trait Function12[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, +R] extends AnyRef
A function of 12 parameters.
Source
trait Function13[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, +R] extends AnyRef
A function of 13 parameters.
Source
trait Function14[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, -T14, +R] extends AnyRef
A function of 14 parameters.
Source
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.
Source
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.
Source
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.
Source
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.
Source
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.
Source
A function of 2 parameters.
In the following example, the definition of max is a shorthand for the anonymous class definition anonfun2:
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))
}
Source
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.
Source
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.
Source
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.
Source
A function of 3 parameters.
Source
A function of 4 parameters.
Source
A function of 5 parameters.
Source
A function of 6 parameters.
Source
A function of 7 parameters.
Source
A function of 8 parameters.
Source
A function of 9 parameters.
Source
object IArray
An immutable array. An IArray[T]
has the same representation as an Array[T]
, but it cannot be updated. Unlike regular arrays, immutable arrays are covariant.
Source
Int
, a 32-bit signed integer (equivalent to Java's int
primitive type) is a subtype of scala.AnyVal. Instances of Int
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.
Companion | object |
---|
Source
object Int
Companion | class |
---|
Source
Long
, a 64-bit signed integer (equivalent to Java's long
primitive type) is a subtype of scala.AnyVal. Instances of Long
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.
Companion | object |
---|
Source
object Long
Companion | class |
---|
Source
This class implements errors which are thrown whenever an object doesn't match any pattern of a pattern matching expression.
open trait Matchable
The base trait of types that can be safely pattern matched against.
See https://dotty.epfl.ch/docs/reference/other-new-features/matchable.html.
Source
sealed trait NonEmptyTuple extends Tuple
Tuple of arbitrary non-zero arity
Source@SerialVersionUID(5066590221178148012L)
This case object represents non-existent values.
Source
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.???
.
final abstract open class Nothing
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 type Nothing
is uninhabited, it is nevertheless useful in several ways. For instance, the Scala library defines a value scala.collection.immutable.Nil of type List[Nothing]
. Because lists are covariant in Scala, this makes scala.collection.immutable.Nil an instance of List[T]
, for any element of type T
.
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.
final abstract open class Null
Null
is - together with scala.Nothing - at the bottom of the Scala type hierarchy.
Null
is the type of the null
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 assign null
to a variable of type scala.Int.
Source
object Option
Companion | class |
---|
Source@SerialVersionUID(-114498752079829388L)
Represents optional values. Instances of Option
are either an instance of scala.Some or the object None
.
The most idiomatic way to use an scala.Option instance is to treat it as a collection or monad and use map
,flatMap
, filter
, or foreach
:
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 from request.getParameter
, the entire expression results in None
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")
}
Note | Many of the methods in here are duplicative with those in the Traversable 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. |
---|---|
Companion | object |
Source
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 type A
. The function isDefinedAt allows to test dynamically if a value is in the domain of the function.
Even if isDefinedAt
returns true for an a: A
, calling apply(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 calling apply
, because if isDefinedAt
is false, it is not guaranteed apply
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
and apply
.
The main distinction between PartialFunction
and scala.Function1 is that the user of a PartialFunction
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.
|
||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Companion | object |
Source
object PartialFunction
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 }
Companion | class |
---|
Source
trait PolyFunction
Marker trait for polymorphic function types.
This is the only trait that can be refined with a polymorphic method, as long as that method is called apply
, e.g.: PolyFunction { def apply[T_1, ..., T_M](x_1: P_1, ..., x_N: P_N): R } This type will be erased to FunctionN.
Source
object Predef
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 of assert
can be elided at compile time by providing the command line option -Xdisable-assertions
, which raises -Xelide-below
above elidable.ASSERTION
, to the scalac
command.
Variants of assert
intended for use with static analysis tools are also provided: assume
, require
and ensuring
. require
and ensuring
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 from assert
in that if the condition fails, then the caller of the function is to blame rather than a logical error having been made within addNaturals
itself. ensuring
is a form of assert
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.
Source
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.
Source
object Product1
Companion | class |
---|
Source
Product1 is a Cartesian product of 1 component.
Companion | object |
---|
Source
object Product10
Companion | class |
---|
Source
Product10 is a Cartesian product of 10 components.
Companion | object |
---|
Source
object Product11
Companion | class |
---|
Source
Product11 is a Cartesian product of 11 components.
Companion | object |
---|
Source
object Product12
Companion | class |
---|
Source
Product12 is a Cartesian product of 12 components.
Companion | object |
---|
Source
object Product13
Companion | class |
---|
Source
Product13 is a Cartesian product of 13 components.
Companion | object |
---|
Source
object Product14
Companion | class |
---|
Source
Product14 is a Cartesian product of 14 components.
Companion | object |
---|
Source
object Product15
Companion | class |
---|
Source
Product15 is a Cartesian product of 15 components.
Companion | object |
---|
Source
object Product16
Companion | class |
---|
Source
Product16 is a Cartesian product of 16 components.
Companion | object |
---|
Source
object Product17
Companion | class |
---|
Source
Product17 is a Cartesian product of 17 components.
Companion | object |
---|
Source
object Product18
Companion | class |
---|
Source
Product18 is a Cartesian product of 18 components.
Companion | object |
---|
Source
object Product19
Companion | class |
---|
Source
Product19 is a Cartesian product of 19 components.
Companion | object |
---|
Source
object Product2
Companion | class |
---|
Source
trait Product2[@specialized(Int, Long, Double) +T1, @specialized(Int, Long, Double) +T2] extends Product
Product2 is a Cartesian product of 2 components.
Companion | object |
---|
Source
object Product20
Companion | class |
---|
Source
Product20 is a Cartesian product of 20 components.
Companion | object |
---|
Source
object Product21
Companion | class |
---|
Source
Product21 is a Cartesian product of 21 components.
Companion | object |
---|
Source
object Product22
Companion | class |
---|
Source
Product22 is a Cartesian product of 22 components.
Companion | object |
---|
Source
object Product3
Companion | class |
---|
Source
Product3 is a Cartesian product of 3 components.
Companion | object |
---|
Source
object Product4
Companion | class |
---|
Source
Product4 is a Cartesian product of 4 components.
Companion | object |
---|
Source
object Product5
Companion | class |
---|
Source
Product5 is a Cartesian product of 5 components.
Companion | object |
---|
Source
object Product6
Companion | class |
---|
Source
Product6 is a Cartesian product of 6 components.
Companion | object |
---|
Source
object Product7
Companion | class |
---|
Source
Product7 is a Cartesian product of 7 components.
Companion | object |
---|
Source
object Product8
Companion | class |
---|
Source
Product8 is a Cartesian product of 8 components.
Companion | object |
---|
Source
object Product9
Companion | class |
---|
Source
Product9 is a Cartesian product of 9 components.
Companion | object |
---|
Source
An exception that indicates an error during Scala reflection
Source
trait Selectable
A marker trait for objects that support structural selection via selectDynamic
and applyDynamic
Implementation classes should define, or make available as extension methods, the following two method signatures:
def selectDynamic(name: String): Any def applyDynamic(name: String)(args: Any*): Any =
selectDynamic
is invoked for simple selections v.m
, whereas applyDynamic
is invoked for selections with arguments v.m(...)
. If there's only one kind of selection, the method supporting the other may be omitted. The applyDynamic
can also have a second parameter list of java.lang.Class
arguments, i.e. it may alternatively have the signature
def applyDynamic(name: String, paramClasses: Class[_]*)(args: Any*): Any
In this case the call will synthesize Class
arguments for the erasure of all formal parameter types of the method in the structural type.
Companion | object |
---|
Source
object Selectable
Companion | class |
---|
Source@deprecatedInheritance("Scheduled for being final in the future", "2.13.0")
Annotation for specifying the serialVersionUID
field of a (serializable) class.
On the JVM, a class with this annotation will receive a private
, static
, and final
field called serialVersionUID
with the provided value
, which the JVM's serialization mechanism uses to determine serialization compatibility between different versions of a class.
See also |
---|
Source
Short
, a 16-bit signed integer (equivalent to Java's short
primitive type) is a subtype of scala.AnyVal. Instances of Short
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.
Companion | object |
---|
Source
object Short
Companion | class |
---|
final open trait Singleton
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 of Singleton
, 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
See also SIP-23 about Literal-based Singleton Types.
Source@SerialVersionUID(1234815782226070388L)
Class Some[A]
represents existing values of type A
.
Source
trait Specializable
A common supertype for companions of specializable types. Should not be extended in user code.
Companion | object |
---|
Source
object Specializable
Companion | class |
---|
Source
case class StringContext(parts: String*)
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
and f
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 the json
method to StringContext
which can be used for json
string literals.
Value parameters |
|
---|---|
Companion | object |
Source
object StringContext
Companion | class |
---|
Source
final class Symbol extends Serializable
This class provides a simple way to get unique objects for equal strings. Since symbols are interned, they can be compared using reference equality.
Companion | object |
---|
Source
object Symbol
Companion | class |
---|
Source
Tuple of arbitrary arity
Companion | object |
---|
Source
object Tuple
Companion | class |
---|
Source
A tuple of 1 elements; the canonical representation of a scala.Product1.
Value parameters |
|
---|---|
Constructor | Create a new tuple with 1 elements. |
Source
A tuple of 10 elements; the canonical representation of a scala.Product10.
Value parameters |
|
---|---|
Constructor | Create a new tuple with 10 elements. Note that it is more idiomatic to create a Tuple10 via |
Source
A tuple of 11 elements; the canonical representation of a scala.Product11.
Value parameters |
|
---|---|
Constructor | Create a new tuple with 11 elements. Note that it is more idiomatic to create a Tuple11 via |
Source
A tuple of 12 elements; the canonical representation of a scala.Product12.
Value parameters |
|
---|---|
Constructor | Create a new tuple with 12 elements. Note that it is more idiomatic to create a Tuple12 via |
Source
A tuple of 13 elements; the canonical representation of a scala.Product13.
Value parameters |
|
---|---|
Constructor | Create a new tuple with 13 elements. Note that it is more idiomatic to create a Tuple13 via |
Source
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]
A tuple of 14 elements; the canonical representation of a scala.Product14.
Value parameters |
|
---|---|
Constructor | Create a new tuple with 14 elements. Note that it is more idiomatic to create a Tuple14 via |
Source
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]
A tuple of 15 elements; the canonical representation of a scala.Product15.
Value parameters |
|
---|---|
Constructor | Create a new tuple with 15 elements. Note that it is more idiomatic to create a Tuple15 via |
Source
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]
A tuple of 16 elements; the canonical representation of a scala.Product16.
Value parameters |
|
---|---|
Constructor | Create a new tuple with 16 elements. Note that it is more idiomatic to create a Tuple16 via |
Source
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]
A tuple of 17 elements; the canonical representation of a scala.Product17.
Value parameters |
|
---|---|
Constructor | Create a new tuple with 17 elements. Note that it is more idiomatic to create a Tuple17 via |
Source
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]
A tuple of 18 elements; the canonical representation of a scala.Product18.
Value parameters |
|
---|---|
Constructor | Create a new tuple with 18 elements. Note that it is more idiomatic to create a Tuple18 via |
Source
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]
A tuple of 19 elements; the canonical representation of a scala.Product19.
Value parameters |
|
---|---|
Constructor | Create a new tuple with 19 elements. Note that it is more idiomatic to create a Tuple19 via |
Source
A tuple of 2 elements; the canonical representation of a scala.Product2.
Value parameters |
|
---|---|
Constructor | Create a new tuple with 2 elements. Note that it is more idiomatic to create a Tuple2 via |
Source
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]
A tuple of 20 elements; the canonical representation of a scala.Product20.
Value parameters |
|
---|---|
Constructor | Create a new tuple with 20 elements. Note that it is more idiomatic to create a Tuple20 via |
Source
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]
A tuple of 21 elements; the canonical representation of a scala.Product21.
Value parameters |
|
---|---|
Constructor | Create a new tuple with 21 elements. Note that it is more idiomatic to create a Tuple21 via |
Source
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]
A tuple of 22 elements; the canonical representation of a scala.Product22.
Value parameters |
|
---|---|
Constructor | Create a new tuple with 22 elements. Note that it is more idiomatic to create a Tuple22 via |
Source
A tuple of 3 elements; the canonical representation of a scala.Product3.
Value parameters |
|
---|---|
Constructor | Create a new tuple with 3 elements. Note that it is more idiomatic to create a Tuple3 via |
Source
A tuple of 4 elements; the canonical representation of a scala.Product4.
Value parameters |
|
---|---|
Constructor | Create a new tuple with 4 elements. Note that it is more idiomatic to create a Tuple4 via |
Source
A tuple of 5 elements; the canonical representation of a scala.Product5.
Value parameters |
|
---|---|
Constructor | Create a new tuple with 5 elements. Note that it is more idiomatic to create a Tuple5 via |
Source
A tuple of 6 elements; the canonical representation of a scala.Product6.
Value parameters |
|
---|---|
Constructor | Create a new tuple with 6 elements. Note that it is more idiomatic to create a Tuple6 via |
Source
A tuple of 7 elements; the canonical representation of a scala.Product7.
Value parameters |
|
---|---|
Constructor | Create a new tuple with 7 elements. Note that it is more idiomatic to create a Tuple7 via |
Source
A tuple of 8 elements; the canonical representation of a scala.Product8.
Value parameters |
|
---|---|
Constructor | Create a new tuple with 8 elements. Note that it is more idiomatic to create a Tuple8 via |
Source
A tuple of 9 elements; the canonical representation of a scala.Product9.
Value parameters |
|
---|---|
Constructor | Create a new tuple with 9 elements. Note that it is more idiomatic to create a Tuple9 via |
Source
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.
Source
Unit
is a subtype of scala.AnyVal. There is only one value of type Unit
, ()
, and it is not represented by any object in the underlying runtime system. A method with return type Unit
is analogous to a Java method which is declared void
.
Companion | object |
---|
Source@compileTimeOnly("`Unit` companion object is not allowed in source; instead, use `()` for the unit value")
object Unit
Companion | class |
---|
Source@implicitNotFound(msg = "No singleton value available for ${T}.")
ValueOf[T]
provides the unique value of the type T
where T
is a type which has a single inhabitant. Eligible types are singleton types of the form stablePath.type
, Unit and singleton types corresponding to value literals.
Instances of ValueOf[T]
are provided implicitly 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 modulo M
. 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 argument m
of type ValueOf[M]
.
Source@getter @setter @beanGetter @beanSetter @field @deprecatedInheritance("Scheduled for being final in the future", "2.13.0")
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
@deprecated
in the Scala language and its standard library
A 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.)
Value parameters |
|
---|---|
See also | The official documentation on binary compatibility. |
Source@getter @setter @beanGetter @beanSetter
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 be final
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
// ^
Value parameters |
|
---|---|
See also |
Source@param @deprecatedInheritance("Scheduled for being final in the future", "2.13.0")
An annotation that designates that the name of a parameter is deprecated.
Using this name in a named argument generates a deprecation warning.
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)
^
Source@getter @setter @beanGetter @beanSetter @deprecatedInheritance("Scheduled for being final in the future", "2.13.0")
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 be final
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
// ^
Value parameters |
|
---|---|
See also |
Source@deprecatedInheritance("Scheduled for being final in the future", "2.13.0")
class inline extends StaticAnnotation
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
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, see -opt-inline-from:help
). If inlining is not possible, for example because the method is not final, an optimizer warning will be issued. See -opt-warnings: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
Source
object language
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
Source
object languageFeature
Source
class main extends Annotation
An annotation that designates a main function
Source@deprecatedInheritance("Scheduled for being final in the future", "2.13.0")
class native extends StaticAnnotation
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).
Source
final class noinline extends StaticAnnotation
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
Source
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] ..
Source
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()
}
Source@field
final class transient extends StaticAnnotation
Source
final class unchecked extends Annotation
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 }
}
Source@experimental
object unsafeExceptions
Source@field
final class volatile extends StaticAnnotation
Types
type & = [X0, X1] =>> X0 & X1
The intersection of two types.
See https://dotty.epfl.ch/docs/reference/new-types/intersection-types.html.
Source
Source
Source
Source
type BigDecimal = BigDecimal
Source
Source
Source
Source
Source
type EmptyTuple = EmptyTuple.type
A tuple of 0 elements
Source
Source
Source
Source
type Fractional[T] = Fractional[T]
Source
opaque type IArray[+T]
Source
Source
Source@migration("scala.IndexedSeq is now scala.collection.immutable.IndexedSeq instead of scala.collection.IndexedSeq", "2.13.0")
type IndexedSeq[+A] = IndexedSeq[A]
Source
Source
Source
Source
type IterableOnce[+A] = IterableOnce[A]
Source
Source
Source
Source
Source
Source
Source
Source
Source
Source
Source
type PartialOrdering[T] = PartialOrdering[T]
Source
type PartiallyOrdered[T] = PartiallyOrdered[T]
Source
Source
Source
type RuntimeException = RuntimeException
Source@migration("scala.Seq is now scala.collection.immutable.Seq instead of scala.collection.Seq", "2.13.0")
Source
type Serializable = Serializable
Source
type StringBuilder = StringBuilder
Source
Source
Source
Source
type | = [X0, X1] =>> X0 | X1
The union of two types.
See https://dotty.epfl.ch/docs/reference/new-types/union-types.html.
Concrete fields
Source
Source
Source
val ::: ::.type
Source
val AnyRef: Specializable
Source
val BigDecimal: BigDecimal.type
Source
Source
Source
Source
val Fractional: Fractional.type
Source
val IndexedSeq: IndexedSeq.type
Source
Source
Source
Source
Source
val Left: Left.type
Source
Source
Source
Source
Source
Source
Source
val Right: Right.type
Source
Source
val StringBuilder: StringBuilder.type
Source
© 2002-2022 EPFL, with contributions from Lightbend.
Licensed under the Apache License, Version 2.0.
https://scala-lang.org/api/3.1.1/scala.html