ThePredef object provides definitions that are accessible in all Scala compilation units without explicit qualification.
Predef provides type aliases for types which are commonly used, such as the immutable collection typesscala.collection.immutable.Map andscala.collection.immutable.Set.
For basic console output,Predef provides convenience methodsprint andprintln, which are aliases of the methods in the objectscala.Console.
A set ofassert 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 ofassert 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 ofaddNaturals 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.
A number of commonly applied implicit conversions are also defined here, and in the parent typescala.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 ofscala.Array.
Utility Methods
??? can be used for marking methods that remain to be implemented.
??? can be used for marking methods that remain to be implemented.
NotImplementedErrorwhen??? is invoked.
Retrieve the runtime representation of a class type.
Retrieve the runtime representation of a class type.classOf[T] is equivalent to the class literalT.class in Java.
The runtimeClass representation of typeT.
val listClass = classOf[List[_]]// listClass is java.lang.Class[List[_]] = class scala.collection.immutable.Listval mapIntString = classOf[Map[Int,String]]// mapIntString is java.lang.Class[Map[Int,String]] = interface scala.collection.immutable.MapA method that returns its input value.
A method that returns its input value.
type of the input value x.
the value of typeA to be returned.
the valuex.
Summon an implicit value of typeT.
Summon an implicit value of typeT. Usually, the argument is not passed explicitly.
the type of the value to be summoned
the implicit value of typeT
Used to mark code blocks as being expressions, instead of being taken as part of anonymous classes and the like.
Used to mark code blocks as being expressions, instead of being taken as part of anonymous classes and the like. This is just a different name foridentity.
Separating code blocks fromnew:
val x = new AnyRef{ val y = ... println(y)}// the { ... } block is seen as the body of an anonymous classval x = new AnyRef{ val y = ... println(y)}// an empty line is a brittle "fix"val x = new AnyReflocally { val y = ... println(y)}// locally guards the block and helps communicate intentRetrieve the single value of a type with a unique inhabitant.
Retrieve the single value of a type with a unique inhabitant.
object Fooval foo = valueOf[Foo.type]// foo is Foo.type = Fooval bar = valueOf[23]// bar is 23.type = 23Assertions
These methods support program verification and runtime correctness.
Tests an expression, throwing anAssertionError if false.
Tests an expression, throwing anAssertionError if false. Calls to this method will not be generated if-Xelide-below is greater thanASSERTION.
the expression to test
Tests an expression, throwing anAssertionError if false.
Tests an expression, throwing anAssertionError if false. Calls to this method will not be generated if-Xelide-below is greater thanASSERTION.
the expression to test
a String to include in the failure message
Tests an expression, throwing anAssertionError if false.
Tests an expression, throwing anAssertionError if false. This method differs from assert only in the intent expressed: assert contains a predicate which needs to be proven, while assume contains an axiom for a static checker. Calls to this method will not be generated if-Xelide-below is greater thanASSERTION.
the expression to test
Tests an expression, throwing anAssertionError if false.
Tests an expression, throwing anAssertionError if false. This method differs from assert only in the intent expressed: assert contains a predicate which needs to be proven, while assume contains an axiom for a static checker. Calls to this method will not be generated if-Xelide-below is greater thanASSERTION.
the expression to test
a String to include in the failure message
Tests an expression, throwing anIllegalArgumentException if false.
Tests an expression, throwing anIllegalArgumentException if false. This method is similar toassert, but blames the caller of the method for violating the condition.
the expression to test
Tests an expression, throwing anIllegalArgumentException if false.
Tests an expression, throwing anIllegalArgumentException if false. This method is similar toassert, but blames the caller of the method for violating the condition.
a String to include in the failure message
the expression to test
Console Output
These methods provide output via the console.
Prints an object toout using itstoString method.
Prints an object toout using itstoString method.
the object to print; may be null.
Prints its arguments as a formatted string to the default output, based on a string pattern (in a fashion similar to printf in C).
Prints its arguments as a formatted string to the default output, based on a string pattern (in a fashion similar to printf in C).
The interpretation of the formatting patterns is described injava.util.Formatter.
Consider using thef interpolator as more type safe and idiomatic.
the pattern for formatting the arguments.
the arguments used to instantiate the pattern.
java.lang.IllegalArgumentException if there was a problem with the format string or arguments
Prints a newline character on the default output.
Prints out an object to the default output, followed by a newline character.
Prints out an object to the default output, followed by a newline character.
the object to print.
Aliases
These aliases bring selected immutable types into scope without any imports.
Allows destructuring tuples with the same syntax as constructing them.
Allows destructuring tuples with the same syntax as constructing them.
val tup = "foobar" -> 3val c = tup match { case str -> i => str.charAt(i)}TheString type in Scala has all the methods of the underlyingjava.lang.String, of which it is just an alias.
TheString type in Scala has all the methods of the underlyingjava.lang.String, of which it is just an alias.
In addition, extension methods inscala.collection.StringOps are added implicitly through the conversionaugmentString.
String Conversions
Conversions from String to StringOps or WrappedString.
Implicit Classes
These implicit classes add useful extension methods to every type.
Injects String concatenation operator+ to any classes.
Injects String concatenation operator+ to any classes.
[Since version 2.13.0]Implicit injection of + is deprecated. Convert to String to call +Injects String concatenation operator+ to any classes.
Injects String concatenation operator+ to any classes.
[Since version 2.13.0]Implicit injection of + is deprecated. Convert to String to call +CharSequence Wrappers
Wrappers that implements CharSequence and were implicit classes.
Java to Scala
Implicit conversion from Java primitive wrapper types to Scala equivalents.
Scala to Java
Implicit conversion from Scala AnyVals to Java primitive wrapper types equivalents.
Array to ArraySeq
Conversions from Arrays to ArraySeqs.
A type supporting Self-based type classes.
A type supporting Self-based type classes.
A is TC
expands to
TC { type Self = A }
which is what is needed for a context bound[A: TC].
Summon a given value of typeT. Usually, the argument is not passed explicitly.
Summon a given value of typeT. Usually, the argument is not passed explicitly.
the type of the value to be summoned
the given value typed: the provided type parameter
Strips away the nullability from a value. Note that.nn performs a checked cast, so if invoked on anull value it will throw anNullPointerException.
Strips away the nullability from a value. Note that.nn performs a checked cast, so if invoked on anull value it will throw anNullPointerException.
val s1: String | Null = "hello"val s2: String = s1.nnval s3: String | Null = nullval s4: String = s3.nn // throw NullPointerExceptionEnables an expression of typeT|Null, whereT is a subtype ofAnyRef, to be checked fornull usingeq rather than only==. This is needed becauseNull no longer haseq orne methods, only== and!= inherited fromAny.
Enables an expression of typeT|Null, whereT is a subtype ofAnyRef, to be checked fornull usingeq rather than only==. This is needed becauseNull no longer haseq orne methods, only== and!= inherited fromAny.
Enables an expression of typeT|Null, whereT is a subtype ofAnyRef, to be checked fornull usingne rather than only!=. This is needed becauseNull no longer haseq orne methods, only== and!= inherited fromAny.
Enables an expression of typeT|Null, whereT is a subtype ofAnyRef, to be checked fornull usingne rather than only!=. This is needed becauseNull no longer haseq orne methods, only== and!= inherited fromAny.
Asserts that a term should be exempt from static checks that can be reliably checked at runtime.
Asserts that a term should be exempt from static checks that can be reliably checked at runtime.
val xs: Option[Int] = Option(1)xs.runtimeChecked match case Some(x) => x // `Some(_)` can be checked at runtime, so no warningval xs: List[Int] = List(1,2,3)val y :: ys = xs.runtimeChecked // `_ :: _` can be checked at runtime, so no warningAn implicit of typeA => A is available for allA because it can always be implemented using the identity function.
An implicit of typeA => A is available for allA because it can always be implemented using the identity function. This also means that an implicit of typeA => B is always available whenA <: B, because(A => A) <: (A => B).
We prefer the java.lang.* boxed types to these wrappers in any potential conflicts.
We prefer the java.lang.* boxed types to these wrappers in any potential conflicts. Conflicts do exist because the wrappers need to implement ScalaNumber in order to have a symmetric equals method, but that implies implementing java.lang.Number as well.
Note - these are inlined because they are value classes, but the call to xxxWrapper is not eliminated even though it does nothing. Even inlined, every call site does a no-op retrieval of Predef's MODULE$ because maybe loading Predef has side effects!
[Since version 2.13.0]implicit conversions from Array to immutable.IndexedSeq are implemented by copying; use `toIndexedSeq` explicitly if you want to copy, or use the more efficient non-copying ArraySeq.unsafeWrapArray