"Scala" Scala's Predef object

Source: Internet
Author: User

Implicit references (implicit Import)

Scala automatically adds several implicit references to each program, just as the Java program automatically adds a Java.lang package. In Scala, the contents of the following three packages are implicitly referenced to each program. The difference is that Scala also implicitly adds a reference to the Predef, which greatly facilitates the programmer's work.

import// in JVM projects, or system namespace in .NETimport scala._     // everything in the scala packageimport Predef._    // everything in the Predef object

The above three packages contain common types and methods. The Java.lang package contains common Java language types and, if in a. NET environment, references the System namespace. Similarly, Scala also implicitly references the Scala package, which is the introduction of commonly used Scala types.

Please note
The order of the three statements above hides a bit of a mystery. We know that, in general, if import comes in two packages have a certain type of definition, for example, the same program, that is, quoted ' Scala.collection.mutable.Set ' and quoted ' Import Scala.collection.immutable.Set ' The compiler will prompt that it cannot determine which Set to use. Implicit references here are different, and if you have the same type, the type of the later package will hide the previous one. For example, Java.lang and Scala have StringBuilder in two packages, in which case the one defined in the Scala package is used. The definition in Java.lang is hidden, unless the display uses Java.lang.StringBuilder.

Predef object Predef provides common functions

Package Predef objects in Scala contain many useful methods. For example, the Scala source file writes down the println statement, and the actual call is the Predef println,Predef.println call Console.println , the complete real work.

def print(x: Any) = Console.print(x)def println() = Console.println()def println(x: Any) = Console.println(x)def printf(text: String, xs: Any*) = Console.print(text.format(xs: _*))

Assert function assert and related functions are also defined in Predef:

/** Tests An expression, throwing a ' assertionerror ' if false.* Calls to this method would not be generated if '-xeli De-below ' * is at least ' assertion '. * * @see elidable* @param assertion the expression to test*/@elidable(assertion)defASSERT (Assertion:boolean) {if(!assertion)Throw NewJava.lang.AssertionError ("Assertion failed")}/** Tests An expression, throwing a ' assertionerror ' if false.* Calls to this method would not be generated if '-xeli De-below ' * is at least ' assertion '. * * @see elidable* @param assertion the expression to test*  @param message A String to include in the failure message*/@elidable(assertion)@inlineFinal defASSERT (Assertion:boolean, message: = = any) {if(!assertion)Throw NewJava.lang.AssertionError ("Assertion failed:"+ message)}
Predef Defining type Aliases

Predef is an object that defines some type aliases in this object, such as:

scala.collection.immutable.List         // to force Nil, :: to be seen.type Function[-A, +B] = Function1[A, B]type Map[A, +B] = immutable.Map[A, B]type Set[A]     = immutable.Set[A]val Map         = immutable.Mapval Set         = immutable.Set

Now we know that using the collection directly, such as List,map,set, uses the objects in the immutable package, which is defined in the predef.

Implicit conversions

The Predef object defines commonly used implicit conversions, such as:

finalclass any2stringadd[A](private val self: A) extends AnyVal {  def +(other: String): String = String.valueOf(self) + other}

The implicit conversion, which adds a method to all subtypes of Anyval +(other: String): String , facilitates the addition of other value types when printing or other string manipulation.

Again such as:

@inlinedefnew StringOps(x)@inlinedef unaugmentString(x: StringOps): String = x.repr

This implicit conversion allows us to freely use the Stringops method on string.
Similarly, the rich Wrapper of numeric types is implemented in this way.

Scala programmers can be less concerned with boxing and unboxing, which is also because the Predef object defines a direct implicit conversion of the Scala value type to the Java base type.

ImplicitdefByte2byte (X:byte) = java.lang.Byte.valueOf (x) implicitdefShort2short (X:short) = java.lang.Short.valueOf (x) implicitdefChar2character (X:char) = java.lang.Character.valueOf (x) implicitdefInt2integer (X:int) = java.lang.Integer.valueOf (x) implicitdefLong2long (X:long) = java.lang.Long.valueOf (x) implicitdefFloat2float (x:float) = java.lang.Float.valueOf (x) implicitdefDouble2double (x:double) = java.lang.Double.valueOf (x) implicitdefBoolean2boolean (X:boolean) = java.lang.Boolean.valueOf (x) implicitdefByte2byte (x:java.lang.byte): Byte = x.bytevalueimplicitdefShort2short (x:java.lang.short): short = x.shortvalueimplicitdefCharacter2char (x:java.lang.character): Char = x.charvalueimplicitdefInteger2int (x:java.lang.integer): Int = x.intvalueimplicitdefLong2long (x:java.lang.long): Long = x.longvalueimplicitdefFloat2float (x:java.lang.float): Float = x.floatvalueimplicitdefDouble2double (x:java.lang.double): Double = x.doublevalueimplicitdefBoolean2boolean (X:java.lang.boolean): Boolean = X.booleanvalue

About Packing (Boxing) and unpacking (unboxing)
Readers familiar with languages such as Java or C # will know that boxing refers to converting the original type to a reference type (object) for an action that requires an object, and unpacking the object to the original type for a scene that requires the original type.
Because the numeric type itself is already a class object, there is no need for boxing (boxing) and unboxing (unboxing) operations in Scala. Of course, the Scala code will eventually run on the JVM, so in practice there will always be boxes of Scala class objects and unpacking into Java primitive value types, but these operations are transparent and the programmer does not need to care (in fact, this is done by the implicit conversion defined in predef).

Resources

PREDEF Official Standard library documentation
Implicit references (implicit Import) and Predef

reprint Please indicate the author Jason Ding and its provenance
Gitcafe Blog Home page (http://jasonding1354.gitcafe.io/)
GitHub Blog Home page (http://jasonding1354.github.io/)
CSDN Blog (http://blog.csdn.net/jasonding1354)
Jane Book homepage (http://www.jianshu.com/users/2bd9b48f6ea8/latest_articles)
Google search jasonding1354 go to my blog homepage

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Scala" Scala's Predef object

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.