[Scala Basic Series 04] Scala Basic types

Source: Internet
Author: User

Numeric type of 1.Scala

Scala's numeric types are similar to Java's, and their scope is consistent with Java. Unlike Java, they are objects and are instances of the corresponding numeric classes. Scala provides powerful support for these numeric types through rich-Wrapper classes.

1.1. Numeric type

Scala's numeric type and range of values are shown in the table below.

    • Boolean:true or False
    • Byte:8 bit, signed (2-7 ~ 27-1)
    • Short:16 bit, signed (2-15 ~ 215-1)
    • Int:32 bit, signed (2-31 ~ 231-1)
    • Long:64 bit, signed (2-63 ~ 263-1)
    • Char:16 bit, unsigned (0 ~ 216-1)
    • Float:32 bit, single-precision floating-point number
    • Double:64 bit, double-precision floating-point number

You can use these types just like in Java. In fact, however, Scala's type system is not the same as in Java or other languages, such as C # or Java, and in Scala, the basic type is class, for example, the int type, from Scala. Int, every number, is Scala. An instance of Int. A unified type system, the unification of primitive types and classes, is a feature of Scala that makes Scala more object-oriented than languages such as Java and C #.

Please note
Numeric types are defined as abstract and final, which means that an instance of a value type cannot be obtained by new. You can create instances of them only through text (Literal).

1.2. 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).

1.3. Rich packaging Class (Rich Wrapper)

As mentioned above, you can use basic types just as you would in Java, but Scala actually provides a lot of methods for basic types. These methods are in rich packaging (rich Wrapper), for example, int corresponds to SCALA.RUNTIME.RICHINT. Each basic type has a corresponding rich wrapper class. The basic type, when necessary, is converted to the corresponding rich wrapper class by an implicit conversion, thus invoking the method provided by the rich wrapper class.

Implicit conversion is a very important technique for Scala, and the following article will cover it.
Let's write a few lines of code to see the powerful features of Richint.

Val N1 = 2 Max 3println ("2 max 3 =" +=-1. ABSPRINTLN (" -1.abs =" += 1 to 5println ("1 to 5 =" += 1. Isvalidcharprintln ("1.isValidChar =" +=-1. isvalidcharprintln c8> " -1.isvalidchar =" + N5)
2.Scala strings (String)

String is a very common type, in essence a series of char, but because it is too common, in many ways have special treatment, in most programming languages will be listed separately.

The string in Scala is a string that is borrowed directly from Java, meaning that string is just an alias for java.lang.String, and the source code is similar to:

Type String = java.lang.String

However, since string is actually a series of immutable collections of char, most of the operations for collections in Scala can be used in string, specifically, These methods of string exist in the class Scala.collection.immutable.StringOps. Because the string can be implicitly converted to stringops when needed, there is no need for any additional conversions, which can be used by string. as shown below.

Val str = "Hello"= Str.drop (2)  //"Llo"println ("\" hello\ ". Drop (2) =" +//  "Hel"println ("\" Hello\ ". Dropright (2) =" +//"Heo"println ("\" Hello\ ". Filter (_! = ' l ') = "+ = Str.intersect (" World ")  //" Lo "println (" \ "Hello\"). Intersect (\ "world\") = "+ R4)

Like Java or C #, a string is immutable, and a string is manipulated to get a new string instance. Therefore, use StringBuilder if you need to operate a string frequently.

New stringbuilderbuilder.append ("Hello") builder.append (", World"+ = '! ') Builder.insert (0, "Me:") println (builder)    // Me:hello, world!
Uniform type of 3.Scala class-level 3.1.Scala

In Scala, all values are class objects, and all classes, including value types, end up inheriting from a uniform root type any. The unified type is another feature of Scala. More specifically, Scala also defines several underlying classes (Bottom class), such as null and nothing. The class hierarchy diagram is shown below.

3.1.1. Top level class any

Any is the topmost class, which means that all classes are sub-types of any and can call methods of the Any class. The top level class any provides the following methods that can be called by any Scala object.

final def = = (that:any): Booleanfinal def! =(that:any): Booleandef equals (that:any): Boo Leandef # #: Intdef hashcode:intdef tostring:string

Please note
In the above method, = =,! = is different from Java. In Scala, = = is always the same as equals, and! = is the negation. = = and! = are final and therefore cannot be overloaded. To compare a reference to an object, you use the Anyref eq method.

3.1.2. Underlying class null and nothing

Null is a subtype of all reference types, and nothing is a subtype of all types. The null class has only one instance object, NULL, similar to a null reference in Java. Because NULL is a subtype of all reference types, this means that null can be assigned to any reference type, but not to a value type.

Perhaps you ask, is it possible to assign an instance object of the Nothing class to a value type. The answer is no, because the Nothing class has no instances and none. What does the Nothing class with no instance do?

Nothing, which can be used as the return type of a method without a normal return value, is very intuitive to tell you that this method does not return normally, and because nothing is a subclass of any other type, he can also be compatible with methods that require return values. This sentence is not very well understood, we use an example to illustrate. Scala.sys has two methods of error and exit, the source code is as follows:

Throw New  = exit (0)

By returning the type nothing, we know that the error method and the Exit method do not return normally. But when we call them, we can be compatible with the required return values, such as:

Def divide (X:int, y:int): Int = {  if (y = = 0) error ("Divide by Zero"  )else x / y}

The Divide method above requires an int value to be returned, but nothing is acceptable if there is an error.

Another use is where there is generics, because Scala supports covariance (it doesn't matter if you don't understand covariance), nothing can replace other types when necessary. For example List[Nothing] , it can be used as any type List[T] . Exactly, type List[Nothing] , has a particular instance, Nil . So Nil it can be List[T] used as an arbitrary instance.

3.1.3.Unit type

As you can see in the class hierarchy diagram, there is a special type in the subtype of Anyval, Unit. The unit type is used to identify a procedure, that is, a function that does not have a definite return value. This shows that the unit is similar to void in Java. The unit has only one instance, () and this instance has no real meaning.

Reference documents:

Http://meetfp.com/zh/scala-basic/class-hierarchy

[Scala Basic Series 04] Scala Basic types

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.