Scala Basics
Scala Basics
Features
Scala is object-oriented
Scala is a pure object-oriented language in the sense that every value is an object. Types and
behavior of objects are described by classes and traits.
Scala is functional
Scala is also a functional language in the sense that every function is a value and every value is
an object so ultimately every function is an object.
Scala provides a lightweight syntax for defining anonymous functions, it supports higher-order
functions, it allows functions to be nested, and supports currying.
Fields − Each object has its unique set of instance variables, which are called fields. An
object's state is created by the values assigned to these fields.
Closure − A closure is a function, whose return value depends on the value of one or
more variables declared outside this function.
Traits − A trait encapsulates method and field definitions, which can then be reused by
mixing them into classes. Traits are used to define object types by specifying the
signature of the supported methods.
We can execute a Scala program in two modes
1) Interactive mode
2) Script mode.
1) Interactive Mode
Open the command prompt and use the following command to open Scala.
\>scala
Type the following text to the right of the Scala prompt and press the Enter key −
scala> println("Hello, Scala");
2) Script Mode
Open notepad and add the following code into it.
object Demo
{
def main(args: Array[String])
{
println("Hello, World")
}
}
Class Names − For all class names, the first letter should be in Upper Case. If several
words are used to form a name of the class, each inner word's first letter should be in
Upper Case.
Example − class MyFirstScalaClass.
Method Names − All method names should start with a Lower Case letter. If multiple
words are used to form the name of the method, then each inner word's first letter should be
in Upper Case.
Example − def myMethodName
Program File Name − Name of the program file should exactly match the object name. When
saving the file you should save it using the object name and append ‘.scala’ to the end of the
name.
Example − Assume 'HelloWorld' is the object name.
Then the file should be saved as 'HelloWorld.scala'.
def main(args: Array[String]) − Scala program processing starts from the main() method
which is a mandatory part of every Scala Program.
Comments in Scala
Single Line Comment
When you want only one line of a comment in Scala, you can use the characters ‘//’ preceding
the comment.
Example
// This is Comment
MultiLine comment
When your comments will span more than one line, you can use a multiline comment. To declare
it, we use the characters ‘/*’ and ‘*/’ around the comment.
Example
/*
This is the first line of a multiline comment.
This is the middle line of a multiline comment.
And this is the last line of a multiline comment.
*/
Documentation Comments
A documentation comment is available for quick documentation lookup.
To declare such a comment, type the characters ‘/**’, and then type something, or press Enter
and end such a comment by ‘*/’
Example
. /**
* This is a documentation comment
* This is a demo
*/
Scala Identifiers
All Scala components require names.
Names used for objects, classes, variables and methods are called identifiers.
A keyword cannot be used as an identifier and identifiers are case-sensitive.
Scala supports four types of identifiers.
Alphanumeric Identifiers
An alphanumeric identifier starts with a letter or an underscore, which can be followed by
further letters, digits, or underscores.
The '$' character is a reserved keyword in Scala and should not be used in identifiers.
Legal alphanumeric identifiers − age, salary, _value, _1_value
Operator Identifiers
An operator identifier consists of one or more operator characters.
Operator characters are printable ASCII characters such as +, :, ?, ~ or #.
Legal operator identifiers − + ++ ::: <?> :>
Mixed Identifiers
A mixed identifier consists of an alphanumeric identifier, which is followed by an underscore
and an operator identifier.
Legal mixed identifiers − unary_+, myvar_=
Literal Identifiers
A literal identifier is an arbitrary string enclosed in back ticks (` . . . `).
Legal literal identifiers − `x` `<clinic>` `yield`
Keywords
Keywords are reserved words in Scala.
These reserved words may not be used as constant or variable or any other identifier names.
Mutable Variable
These variables are those variables which allow us to change a value after the declaration of a
variable.
Mutable variables are defined by using the var keyword.
Example
var data = 100;
data = 101; // It works, No error.
Immutable Variable
These variables are those variables which do not allow you to change a value after the
declaration of a variable.
Immutable variables are defined by using the val keyword.
Example
val data = 100;
data = 101; // Error: reassignment to val
Sr. Data
Description
No. Type
1 Any The supertype of any type; any object is of type Any
2 AnyRef The supertype of any reference type
3 Boolean Either the literal true or the literal false
4 Byte 8 bit signed value. Range from -128 to 127
5 Short 16 bit signed value. Range -32768 to 32767
6 Int 32 bit signed value. Range -2147483648 to 2147483647
64 bit signed value. -9223372036854775808 to
7 Long
9223372036854775807
8 Float 32 bit IEEE 754 single-precision float
9 Double 64 bit IEEE 754 double-precision float
10 Char 16 bit unsigned Unicode character. Range from U+0000 to U+FFFF
11 String A sequence of Chars
12 Unit Corresponds to no value
13 Null null or empty reference
14 Nothing The subtype of every other type; includes no values
Data Type Default Value Size
def readBoolean(): Boolean Reads a boolean value from an entire line of the
default input.
def readByte(): Byte Reads a byte value from an entire line of the default
input
def readShort(): Short Reads a short value from an entire line of the default
input.
def readInt(): Int Reads an int value from an entire line of the default
input.
def readLong(): Long Reads an long value from an entire line of the
default input.
def readFloat(): Float Reads a float value from an entire line of the default
input.
def readDouble(): Double Reads a double value from an entire line of the
default input.
def readChar(): Char Reads a char value from an entire line of the default
input.
def readLine(): String Read a full line from the default input.
def readLine(text: String, args: Any*): String Print and flush formatted text to the default output,
and read a full line from the default input.
def readf(format: String): List[Any] Reads in some structured input (from the default
input), specified by a format specifier.
def readf1(format: String): Any Reads in some structured input (from the default
input), specified by a format specifier, returning
only the first value extracted, according to the
format specification.
def readf2(format: String): (Any, Any) Reads in some structured input (from the default
input), specified by a format specifier, returning
only the first two values extracted, according to the
format specification.
def readf3(format: String): (Any, Any, Any) Reads in some structured input (from the default
input), specified by a format specifier, returning
only the first three values extracted, according to the
format specification.
Scala Literals
Integral Literals
Integer literals are usually of type Int, or of type Long when followed by a L or l suffix.
Examples
0
035
21
0xFFFFFFFF
0777L
Boolean Literals
The Boolean literals true and false are members of type Boolean.
Symbol Literals
A symbol literal 'x is a shorthand for the expression scala.Symbol("x").
Symbol is a case class, which is defined as follows.
package scala
final case class Symbol private (name: String)
{
override def toString: String = "'" + name
}
Character Literals
A character literal is a single character enclosed in quotes.
The character is either a printable Unicode character or is described by an escape sequence.
Examples
'a'
'\u0041'
'\n'
'\t'
String Literals
A string literal is a sequence of characters in double quotes.
The characters are either printable Unicode character or are described by escape sequences.
Examples
"Hello,\nWorld!"
"This string contains a \" character."
Multi-Line Strings
A multi-line string literal is a sequence of characters enclosed in triple quotes """ ... """. The
sequence of characters is arbitrary, except that it may contain three or more consecutive quote
characters only at the very end.
Characters must not necessarily be printable, newlines or other control characters are also
permitted.
Examples
"""the present string
spans three
lines."""
Null Values
The null value is of type scala.Null and is thus compatible with every reference type.
It denotes a reference value which refers to a special "null" object.
Escape Sequences
The following escape sequences are recognized in character and string literals.
\b \u0008 backspace BS
\t \u0009 horizontal tab HT
\n \u000c formfeed FF
\f \u000c formfeed FF
\r \u000d carriage return CR
\" \u0022 double quote "
\' \u0027 single quote .
\\ \u005c backslash \