A data type tells the compiler about the type of the value to be stored in a location. There are no primitive data types unlike in java since everything in Scala is an object.

The following data types are treated as objects in Scala and can call methods on int, String, long etc.

Byte: Byte is an 8 bit signed value.The value ranges from -128 to 127

Short: is an 16 bit signed value ranging from -32768 to 32767

Int: is an 32 bit signed value ranging from -2147483648 to 2147483647

Long: is a 64 bit signed value ranging from -9223372036854775808 to 9223372036854775807

Float: is a 32 bit single precision floating point.

Double: is a 64 bit double precision floating point

Char: is a 16 bit unsigned unicode character ranging from U+0000 to U+FFFF.

String: A sequence of characters enclosed with double quotes.

Boolean: literal with true and false values

AnyRef: Supertype of any reference

Nothing: Subtype of every other type includes no values

Null: Empty reference

Unit: Corresponds to no value

Any: Super type of any type or object of any type

Scala Basic Literals

The basic literals include the following;

Integer literals: Integer literals are of type int,long followed by L or l suffix.Some of the examples of integer literals are 42,42FFF etc..

Floating point Literals: This data type includes float followed by suffix F or f.Examples include 3.12,4.67 etc..

String Literals: A string is a sequence of characters enclosed within the double quotes.

Examples of strings are “Hello World”, “Set of Strings” etc.

Character literals: A character is a single character enclosed in quotes.

Examples include ‘n’, ‘t’ etc.

Multiline Strings: A multiline string are the characters enclosed with triple quotes “”” … “””. Newlines and other controllable characters are permitted and the sequence may be arbitrary. Example of a multiline string is

“””String is a
sequence of
characters.”””

NULL value: The null value denotes a reference value which refers to a null object and null value is of type scala.Null.

Escape Sequence: The following escape sequences are supported in Scala

b: backspace

t: Horizontal tab

f: form feed

n: newline character

r: carriage return

”: double quote

’: single quote

\: backslash

Let us see an example of the escape sequence;


object String {
def main(args: Array[String]) {
println("StringtLiteralnndatatype" );
}
}

Run the above code in the shell as shown below


scala>String.main(null)
String   Literal
datatype
scala>

This output shows that a tab space has been inserted between String and Literal and a new line is inserted printing the datatype. Below image shows it’s execution in Scala shell.

Scala-Data-Types-Example-450x264

That’s all for Scala data types, we will look into more Scala core features in the coming posts.

By admin

Leave a Reply

%d bloggers like this: