[go: up one dir, main page]

0% found this document useful (0 votes)
237 views11 pages

Scala Basics

Scala is a hybrid functional and object-oriented programming language that runs on the Java Virtual Machine. Some key points about Scala include: - Scala smoothly integrates features of object-oriented and functional programming. - It is statically typed, compiled to Java bytecode, and can use existing Java code and libraries. - Scala supports features like immutable data structures, pattern matching, and concurrency which make it well-suited for writing concurrent and parallel programs. - Many companies use Scala because it allows developers to write more concise code that is type-safe and scalable compared to Java.

Uploaded by

Shubham
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
237 views11 pages

Scala Basics

Scala is a hybrid functional and object-oriented programming language that runs on the Java Virtual Machine. Some key points about Scala include: - Scala smoothly integrates features of object-oriented and functional programming. - It is statically typed, compiled to Java bytecode, and can use existing Java code and libraries. - Scala supports features like immutable data structures, pattern matching, and concurrency which make it well-suited for writing concurrent and parallel programs. - Many companies use Scala because it allows developers to write more concise code that is type-safe and scalable compared to Java.

Uploaded by

Shubham
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Scala Basics

 Scala, short for Scalable Language, is a hybrid functional programming language.


 Scala is a modern multi-paradigm programming language designed to express common
programming patterns in a concise, elegant, and type-safe way.
 Scala has been created by Martin Odersky and he released the first version in 2003.
 Scala smoothly integrates the features of object-oriented and functional languages.
 Scala is compiled to run on the Java Virtual Machine.
 Many existing companies, who depend on Java for business critical applications, are turning
to Scala to boost their development productivity, applications scalability and overall
reliability.

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.

Scala is statically typed


Scala, unlike some of the other statically typed languages (C, Pascal, Rust, etc.), does not expect
you to provide redundant type information. You don't have to specify a type in most cases, and
you certainly don't have to repeat it.

Scala runs on the JVM


Scala is compiled into Java Byte Code which is executed by the Java Virtual Machine (JVM).
This means that Scala and Java have a common runtime platform. You can easily move from
Java to Scala.

Scala can Execute Java Code


Scala enables you to use all the classes of the Java SDK and also your own custom Java classes,
or your favorite Java open source projects.

Scala can do Concurrent & Synchronize processing


Scala allows you to express general programming patterns in an effective way.
It reduces the number of lines and helps the programmer to code in a type-safe way.
It allows you to write codes in an immutable manner, which makes it easy to apply concurrency
and parallelism (Synchronize).
When we consider a Scala program, it can be defined as a collection of objects that
communicate via invoking each other’s methods.
Let us now briefly look into what do class, object, methods and instance variables mean.

 Object − Objects have states and behaviors. An object is an instance of a class.


Example − A dog has states - color, name, breed as well as behaviors - wagging,
barking, and eating.

 Class − A class can be defined as a template/blueprint that describes the behaviors/states


that are related to the class.

 Methods − A method is basically a behavior. A class can contain many methods. It is in


methods where the logics are written, data is manipulated and all the actions are
executed.

 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

If Scala is installed in your system, the following output will be displayed −


Welcome to Scala version 2.9.0.1
Type in expressions to have them evaluated.
Type : help for more information.

Type the following text to the right of the Scala prompt and press the Enter key −
scala> println("Hello, Scala");

Output :- Hello, Scala

2) Script Mode
Open notepad and add the following code into it.
object Demo
{
def main(args: Array[String])
{
println("Hello, World")
}
}

 Save the file as − Demo.scala.


 Open the command prompt window and go to the directory where the program file is
saved.
 The ‘scalac’ command is used to compile the Scala program and it will generate a few
class files in the current directory. One of them will be called Demo.class. This is a
bytecode which will run on Java Virtual Machine (JVM) using ‘scala’ command.
 Use the following command to compile and execute your Scala program.
\> scalac Demo.scala
\> scala Demo
 Output :- Hello, World
Basic Syntax
The following are the basic syntaxes and coding conventions in Scala programming.

Case Sensitivity − Scala is case-sensitive,


Example -Identifier Hello and hello would have different meaning in Scala.

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.

class if def final =

object else return finally =>

var case private trait <-

val while protected lazy <:

import do extends type >:

package for super with <%

override forSome extends yield :

new true try sealed -

this false catch match #

implicit null throw @


Variable
Variable is a name which is used to refer memory location. You can create mutable and
immutable variable in scala.
Syntax :- var or val VariableName : DataType = [Initial Value]

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.

Syntax :- var VariableName : DataType = "value";

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.

Syntax :- val VariableName : DataType = "value";

Example
val data = 100;
data = 101; // Error: reassignment to val

Rules for naming variable in Scala


1) Variable name should be in lower case.
2) Variable name can contain letter, digit and two special characters(Underscore(_) and
Dollar($) sign)
3) Variable name must not contain the keyword or reserved word.
4) Starting letter of the variable name should be an alphabet.
5) White space is not allowed in variable name.

Variable Type Inference In Scala


Scala supports variable type inference.
In variable type inference values are directly assigned to the variable without defining its data
type, the Scala compiler automatically resolves which value belongs to which data type.
Example:-
var n=10; //default int type
val name="Sarika"; //default String type
Data Type

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

Boolean False True or false


Byte 0 8 bit signed value (-27 to 27-1)
Short 0 16 bit signed value(-215 to 215-1)
Int 0 32 bit signed value(-231 to 231-1)
Long 0L 64 bit signed value(-263 to 263-1)
Float 0.0F 32 bit IEEE 754 single-precision float
Double 0.0D 64 bit IEEE 754 double-precision float
Char '\u0000' 16 bit unsigned Unicode character(0 to 216-1)
String Null A sequence of characters

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

Floating Point Literal


Floating point literals are of type Float when followed by a floating point type suffix F or f, and
are of type Double otherwise.
Examples
0.0
1e30f
3.14159f
1.0e100
.1

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.

Escape Sequences Unicode Description

\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 \

You might also like