SlideShare a Scribd company logo
Welcome to Scala
Scala
Scala - Scalable Language
● Scala is a modern multi-paradigm programming
language designed to express common programming
patterns in a concise, elegant, and type-safe way
● Integrates the features of object-oriented and
functional languages
Scala
Why Scala?
● Statically Typed
■ Proven correctness before deployment
■ Performance
● Lightweight Composable Syntax
■ Low boilerplate
■ Syntax is very similar to other data centric languages
● Stable
■ Is being used in enterprises, financial sectors, retail, gaming
and more for many years
Scala
Scala - History
2011 Corporate stewardship
2005 Scala 2.0 written in Scala
2003 First Experimental Release
2001 Decided to create even better Java
1990
Martin Odersky (Creator of Scala) made Java better via
generics in the “javac” compiler
Scala
Scala - JVM
● Scala source code gets compiled to Java byte
code
● Resulting bytecode is executed by a JVM - the
Java Virtual Machine
● Java libraries may be used directly in Scala code
and vice versa
Scala
Scala - Hello World - Example
// Create a file hello_world.scala
// using nano hello_world.scala
object HelloWorld {
def main(args: Array[String]) {
println("Hello, world!")
}
}
Scala
Scala - Hello World - Compiling and Running
● Compile using scalac
scalac hello_world.scala
● To run it
scala HelloWorld
Scala
Scala - Interpreter
● scala hello_world.scala
Scala
Scala - Interpreter
To evaluate a single expression, you can use the following:
scala -e 'println("Hello, World!")'
Scala
Scala - Variables
● Variables are reserved memory locations to store values
● Compiler allocates a memory based on the data type of
the variable
Scala
Scala - Variables - Types
● Mutable
● Immutable
Scala
Scala - Variables - Types
● Mutable variables are defined using “var” keyword
○ values can be changed
● Immutable variables are defined using “val” keyword
○ values can not be changed after assignment
Scala
● val x: Int = 8 // Immutable, Read Only
● var y: Int = 7 // Mutable
Scala - Variables - Hands-on
Scala
What is the importance of immutable variables?
● In large systems, we do not want to be in a situation
where a variable's value changes unexpectedly
● In case of threads, APIs, functions and classes, we may
not want some of the variables to change
Scala - Immutable Variables - Importance
Scala
● We can define the variables without specifying their data
type
● Scala compiler can understand the type of the variable
based on the value assigned to it
Scala - Variables - Type Inference
Scala
● var x = "hi" // Type Inference (Scala compiler determines the type)
● var x: String = "hi" // Explicitly specifying the type
Scala - Variables - Type Inference
Scala
● We should always define type of variables explicitly
○ Code will be compiled faster as compiler will not have to spend
time in guessing the type
○ No ambiguity
Scala - Variables - Type Inference
Scala
● A class is a way of creating your own data type
● We can create a data type that represents a customers using a class
● A customer might have states like first name, last name, age,
address and contact number
● A customer class might represent behaviours for how these states
can be transformed like how to change someone’s address or name
● A class is not concrete until it has been instantiated using a new
keyword
Scala - Classes
Scala
class Person(val fname: String, val lname: String, val anage: Int) {
val firstname:String = fname;
val lastname: String = lname;
val age = anage;
}
val obj = new Person("Robin", "Gill", 42);
print(obj.age)
print(obj.firstname)
Scala - Classes - Hands-on
Scala
class Person(val fname: String, val lname: String, val anage: Int) {
val firstname:String = fname;
val lastname: String = lname;
val age = anage;
def getFullName():String = {
return firstname + " " + lastname;
}
}
val obj = new Person("Robin", "Gill", 42);
print(obj.getFullName())
Scala - Classes - Methods - Hands-on
Scala
● A singleton is a class which can have only one instance at any point
in time
● Methods and values that aren’t associated with individual instances
of a class belong in singleton objects
● A singleton class can be directly accessed via its name
● Create a singleton class using the keyword object
Scala - Singleton Objects
Scala
object Hello {
def message(): String = {
return "Hello!!!";
}
}
Scala - Singleton Objects
Scala
● Objects are useful in defining utility methods and constants as they
are not related to any specific instance of the class
Scala - Singleton Objects
Scala
1. def add(x : Int, y : Int) : Int = {
return x + y
}
2. def add(x : Int, y : Int) = { //return type is inferred
x + y //"return" keyword is optional
}
3. //Curly braces are optional on single line blocks
def add(x : Int, y : Int) = x + y
Scala - Functions - Representations
Scala
● Collections provide different ways to store data
● Scala collections hierarchy represents a structure of collections that
can contain data in different ways
Scala - Collections - Overview
Scala
Scala - Collections - Overview
Scala
● An ordered collection of data
● May or may not be indexed
● Array, List, Vector
Scala - Collections - Sequence
Scala
● Contains elements of same type
● Fixed size, ordered sequence of data
● Values are contiguous in memory
● Indexed by position
Scala - Collections - Sequence - Array
Scala
● var languages = Array("Ruby", "SQL", "Python")
● languages(0)
● languages(1) = "C++"
● // Iterate over array
for(x <- languages) {
println(x);
}
Scala - Collections - Sequence - Array
Scala
● List represents linked list with a value and a pointer to the
next element
● Poor performance as data could be anywhere in the
memory
● Theoretically unbounded in size
Scala - Collections - Sequence - List
Scala
● var number_list = List(1, 2, 3)
● number_list :+ 4
Scala - Collections - Sequence - List
Scala
● Bag of data with no duplicates
● Order is not guaranteed
Scala - Collections - Sets
Scala
● var set = Set(76, 5, 9, 1, 2);
● set = set + 9;
● set = set + 20;
● set(5);
● set(14);
Scala - Collections - Sets
Scala
Scala - Collections - Tuples
● Unlike array or list, tuples can hold elements of different
data types
● Example var t = (14, 45.69, "Australia") or
● var t = Tuple3(14, 45.69, "Australia") //Same result
● Can be accessed using a 1-based accessor for each value
Scala
Scala - Collections - Tuples
● t._1 // 14
● t._3 // Australia
● Can be deconstructed into names bound to each value in
the tuple
● Tuples are immutable
Scala
● Collection of key/value pairs
● Allows indexing values by a specific key for fast access
● Java HashMap, Python dictionary
Scala - Collections - Maps
Scala
Scala - Collections - Maps
● var colors = Map("red" -> "#FF0000", "yellow" -> "#FFFF00")
● colors("yellow")
● colors += "green" -> "#008000"
● colors -= "red"
● for ((key,value) <- colors) {
printf("key: %s, value: %sn", key, value)
}
Scala
Scala - Collections - Maps
● Two types of maps
○ Mutable
○ Immutable
● By default, Scala uses the immutable map
● For mutable maps explicitly import
○ import scala.collection.mutable.Map
Scala
Scala - Higher Order Functions
● Higher order function is a function which takes another
function as an argument
● Describes “how” the work to be done in a collection
Scala
● The map applies the function to each value in the
collection and returns a new collection
Scala - Higher Order Functions - Map
Scala
Scala - Higher Order Functions - Map
3 13
7 16
3 + 1 7 + 1 16 + 1
13 + 1
4 14
8 17
Scala
● var list = List(1,2,3)
● list.map(x => x + 1) // List(2, 3, 4)
● list.map(_+ 1) // Same output
Scala - Higher Order Functions - Map
Scala
● flatMap takes a function as an argument and this function
must return a collection
● Returned collection could be empty
● The flatMap applies the function passed to it as argument
on each value in the collection just like map
● The returned collections from each call of function are
then merged together to form a new collection
Scala - Higher Order Functions - flatMap
Scala
● var list = List("Python", "Go")
● list.flatMap(lang => lang + "#") // List(P, y, t, h, o, n, #, G, o,
#)
● list.flatMap(_+ "#") // Same output
Scala - Higher Order Functions - flatMap
Scala
● Filter applies a function to each value in the collection and
returns a new collection with values that satisfy a condition
specified in the function
Scala - Higher Order Functions - Filter
Scala
Scala - Higher Order Functions - Filter
● var list = List("Scala", "R", "Python", "Go", "SQL")
● list.filter(lang => lang.contains("S")) // List(Scala, SQL)
Scala
● Each of the previous higher order functions returned a
new collection after applying the transformation
● At times we do not want the functions to return a new
collection
○ Waste of memory resources on JVM if we do not want
a return value
● foreach applies a function to each value of collection
without returning a new collection
Scala - Higher Order Functions - foreach
Scala
● var list = List("Python", "Go")
● list.foreach(println)
Scala - Higher Order Functions - foreach
Scala
Scala - Higher Order Functions - Reduce
Scala
Scala - Higher Order Functions - Reduce
3 7 13 16
10
23 39
Scala
Scala - Higher Order Functions - Reduce
● In previous example, addition of two variables was called
again and again until all the values got reduced to a single
value
● Please note, in case of reduce input collection should
contain elements of same data type
Scala
Scala - Higher Order Functions - Reduce
● var list = List(3, 7, 13, 16)
● list.reduce((x, y) => x + y) // 39
● list.reduce(_ + _) // same
Scala
import java.util.{Date, Locale}
import java.text.DateFormat
import java.text.DateFormat._
object USDate {
def getDate(): String = {
val now = new Date
val df = getDateInstance(LONG, Locale.US)
return df.format(now)
}
}
Scala - Interaction with Java
Scala
● If we are working on a big project containing hundreds of
source files, it becomes really tedious to compile these files
manually
● We need a build tool to manage the compilation of all
these files
● SBT is build tool for Scala and Java projects, similar to
Java's Maven or ant
Scala - Build Tool - SBT
Scala
● Sample Scala project is located at CloudxLab GitHub repository
https://github.com/singhabhinav/cloudxlab/tree/master/scala/sbt
● Clone the repository
git clone https://github.com/singhabhinav/cloudxlab.git ~/cloudxlab
● Or update the repository
cd ~/cloudxlab && git pull origin master
Scala - Build Tool - SBT - Demo
Scala
● cd ~/cloudxlab/scala/sbt
● Look at the build.sbt file and the directory layout. Scala files must be
located at
src/main/scala
● Run the project using
sbt run
Scala - Build Tool - SBT - Demo
Scala
● Case classes are regular classes that are:
○ Immutable by default
○ Can be pattern matched
○ Compiler automatically generates hashCode and equals
methods, so less boilerplate code
○ Helps in writing more expressive and maintainable code
Scala - Case Classes
Scala
● Sample Scala project is located at CloudxLab GitHub repository
https://github.com/singhabhinav/cloudxlab/tree/master/scala/case_cla
sses
● Clone the repository
git clone https://github.com/singhabhinav/cloudxlab.git ~/cloudxlab
● Or update the repository
cd ~/cloudxlab && git pull origin master
Scala - Case Classes - Demo
Scala
● cd ~/cloudxlab/scala/case_classes
● scala case_class.scala // Run case class demo
● scala pattern_matching.scala // Run pattern matching demo
Scala - Case Classes - Demo
Scala
Thank You
Scala - End

More Related Content

What's hot (20)

PPT
Chicago Data Summit: Apache HBase: An Introduction
Cloudera, Inc.
 
PDF
event mesh cpi Cloud Integration – Connecting to Messaging System... - SAP Co...
HaydarV
 
PDF
Missing data
mandava57
 
PPTX
Key-Value NoSQL Database
Heman Hosainpana
 
PPTX
Data Wrangling
Ashwini Kuntamukkala
 
PPT
Dma unit 1
thamizh arasi
 
PPT
Hadoop hive presentation
Arvind Kumar
 
PDF
Data science workshop
Hortonworks
 
PDF
Growing the Delta Ecosystem to Rust and Python with Delta-RS
Databricks
 
PPT
7. Key-Value Databases: In Depth
Fabio Fumarola
 
PPTX
Hadoop Distributed File System
Rutvik Bapat
 
PDF
Hadoop Overview & Architecture
EMC
 
DOC
Data Mining: Data Preprocessing
Lakshmi Sarvani Videla
 
PDF
Latent Semantic Analysis of Wikipedia with Spark
Sandy Ryza
 
PPTX
Polyglot Persistence
Dr-Dipali Meher
 
PPTX
Lect7 Association analysis to correlation analysis
hktripathy
 
PDF
Simplifying Big Data Analytics with Apache Spark
Databricks
 
PPT
2.4 rule based classification
Krish_ver2
 
PPTX
Hadoop World 2011: Advanced HBase Schema Design - Lars George, Cloudera
Cloudera, Inc.
 
PPTX
Online analytical processing
nurmeen1
 
Chicago Data Summit: Apache HBase: An Introduction
Cloudera, Inc.
 
event mesh cpi Cloud Integration – Connecting to Messaging System... - SAP Co...
HaydarV
 
Missing data
mandava57
 
Key-Value NoSQL Database
Heman Hosainpana
 
Data Wrangling
Ashwini Kuntamukkala
 
Dma unit 1
thamizh arasi
 
Hadoop hive presentation
Arvind Kumar
 
Data science workshop
Hortonworks
 
Growing the Delta Ecosystem to Rust and Python with Delta-RS
Databricks
 
7. Key-Value Databases: In Depth
Fabio Fumarola
 
Hadoop Distributed File System
Rutvik Bapat
 
Hadoop Overview & Architecture
EMC
 
Data Mining: Data Preprocessing
Lakshmi Sarvani Videla
 
Latent Semantic Analysis of Wikipedia with Spark
Sandy Ryza
 
Polyglot Persistence
Dr-Dipali Meher
 
Lect7 Association analysis to correlation analysis
hktripathy
 
Simplifying Big Data Analytics with Apache Spark
Databricks
 
2.4 rule based classification
Krish_ver2
 
Hadoop World 2011: Advanced HBase Schema Design - Lars George, Cloudera
Cloudera, Inc.
 
Online analytical processing
nurmeen1
 

Similar to Scala.pdf (20)

PDF
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLab
CloudxLab
 
PDF
Yes scala can!
amirmoulavi
 
PDF
Scala - core features
Łukasz Wójcik
 
PDF
Programming in scala - 1
Mukesh Kumar
 
PPT
Scala in a nutshell by venkat
Venkateswaran Kandasamy
 
PDF
BCS SPA 2010 - An Introduction to Scala for Java Developers
Miles Sabin
 
PDF
An Introduction to Scala for Java Developers
Miles Sabin
 
PPTX
Scalable Applications with Scala
Nimrod Argov
 
ODP
Introduction To Scala
Basuk
 
ODP
Knolx Session: Introducing Extractors in Scala
Ayush Mishra
 
PDF
An Introduction to Scala - Blending OO and Functional Paradigms
Miles Sabin
 
PDF
Scala for Java Programmers
Eric Pederson
 
PPTX
Taxonomy of Scala
shinolajla
 
PDF
A Brief Introduction to Scala for Java Developers
Miles Sabin
 
PDF
Miles Sabin Introduction To Scala For Java Developers
Skills Matter
 
PDF
Functional programming in Scala
datamantra
 
PPTX
Introduction to Scala
Rahul Jain
 
PPTX
Spark - The Ultimate Scala Collections by Martin Odersky
Spark Summit
 
PDF
Develop realtime web with Scala and Xitrum
Ngoc Dao
 
PPT
Scala Days San Francisco
Martin Odersky
 
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLab
CloudxLab
 
Yes scala can!
amirmoulavi
 
Scala - core features
Łukasz Wójcik
 
Programming in scala - 1
Mukesh Kumar
 
Scala in a nutshell by venkat
Venkateswaran Kandasamy
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
Miles Sabin
 
An Introduction to Scala for Java Developers
Miles Sabin
 
Scalable Applications with Scala
Nimrod Argov
 
Introduction To Scala
Basuk
 
Knolx Session: Introducing Extractors in Scala
Ayush Mishra
 
An Introduction to Scala - Blending OO and Functional Paradigms
Miles Sabin
 
Scala for Java Programmers
Eric Pederson
 
Taxonomy of Scala
shinolajla
 
A Brief Introduction to Scala for Java Developers
Miles Sabin
 
Miles Sabin Introduction To Scala For Java Developers
Skills Matter
 
Functional programming in Scala
datamantra
 
Introduction to Scala
Rahul Jain
 
Spark - The Ultimate Scala Collections by Martin Odersky
Spark Summit
 
Develop realtime web with Scala and Xitrum
Ngoc Dao
 
Scala Days San Francisco
Martin Odersky
 
Ad

Recently uploaded (20)

PDF
Digital water marking system project report
Kamal Acharya
 
PDF
methodology-driven-mbse-murphy-july-hsv-huntsville6680038572db67488e78ff00003...
henriqueltorres1
 
PPT
Footbinding.pptmnmkjkjkknmnnjkkkkkkkkkkkkkk
mamadoundiaye42742
 
PDF
Electrical Machines and Their Protection.pdf
Nabajyoti Banik
 
PDF
AN EMPIRICAL STUDY ON THE USAGE OF SOCIAL MEDIA IN GERMAN B2C-ONLINE STORES
ijait
 
PPTX
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
PDF
REINFORCEMENT LEARNING IN DECISION MAKING SEMINAR REPORT
anushaashraf20
 
PPTX
MODULE 05 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
PDF
mbse_An_Introduction_to_Arcadia_20150115.pdf
henriqueltorres1
 
PPTX
MODULE 03 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
PDF
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
PPT
Testing and final inspection of a solar PV system
MuhammadSanni2
 
PDF
aAn_Introduction_to_Arcadia_20150115.pdf
henriqueltorres1
 
PPTX
Introduction to Internal Combustion Engines - Types, Working and Camparison.pptx
UtkarshPatil98
 
PDF
MODULE-5 notes [BCG402-CG&V] PART-B.pdf
Alvas Institute of Engineering and technology, Moodabidri
 
PPTX
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
PDF
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
PPTX
How Industrial Project Management Differs From Construction.pptx
jamespit799
 
PPT
New_school_Engineering_presentation_011707.ppt
VinayKumar304579
 
PPTX
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
Digital water marking system project report
Kamal Acharya
 
methodology-driven-mbse-murphy-july-hsv-huntsville6680038572db67488e78ff00003...
henriqueltorres1
 
Footbinding.pptmnmkjkjkknmnnjkkkkkkkkkkkkkk
mamadoundiaye42742
 
Electrical Machines and Their Protection.pdf
Nabajyoti Banik
 
AN EMPIRICAL STUDY ON THE USAGE OF SOCIAL MEDIA IN GERMAN B2C-ONLINE STORES
ijait
 
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
REINFORCEMENT LEARNING IN DECISION MAKING SEMINAR REPORT
anushaashraf20
 
MODULE 05 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
mbse_An_Introduction_to_Arcadia_20150115.pdf
henriqueltorres1
 
MODULE 03 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
Testing and final inspection of a solar PV system
MuhammadSanni2
 
aAn_Introduction_to_Arcadia_20150115.pdf
henriqueltorres1
 
Introduction to Internal Combustion Engines - Types, Working and Camparison.pptx
UtkarshPatil98
 
MODULE-5 notes [BCG402-CG&V] PART-B.pdf
Alvas Institute of Engineering and technology, Moodabidri
 
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
How Industrial Project Management Differs From Construction.pptx
jamespit799
 
New_school_Engineering_presentation_011707.ppt
VinayKumar304579
 
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
Ad

Scala.pdf

  • 2. Scala Scala - Scalable Language ● Scala is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way ● Integrates the features of object-oriented and functional languages
  • 3. Scala Why Scala? ● Statically Typed ■ Proven correctness before deployment ■ Performance ● Lightweight Composable Syntax ■ Low boilerplate ■ Syntax is very similar to other data centric languages ● Stable ■ Is being used in enterprises, financial sectors, retail, gaming and more for many years
  • 4. Scala Scala - History 2011 Corporate stewardship 2005 Scala 2.0 written in Scala 2003 First Experimental Release 2001 Decided to create even better Java 1990 Martin Odersky (Creator of Scala) made Java better via generics in the “javac” compiler
  • 5. Scala Scala - JVM ● Scala source code gets compiled to Java byte code ● Resulting bytecode is executed by a JVM - the Java Virtual Machine ● Java libraries may be used directly in Scala code and vice versa
  • 6. Scala Scala - Hello World - Example // Create a file hello_world.scala // using nano hello_world.scala object HelloWorld { def main(args: Array[String]) { println("Hello, world!") } }
  • 7. Scala Scala - Hello World - Compiling and Running ● Compile using scalac scalac hello_world.scala ● To run it scala HelloWorld
  • 8. Scala Scala - Interpreter ● scala hello_world.scala
  • 9. Scala Scala - Interpreter To evaluate a single expression, you can use the following: scala -e 'println("Hello, World!")'
  • 10. Scala Scala - Variables ● Variables are reserved memory locations to store values ● Compiler allocates a memory based on the data type of the variable
  • 11. Scala Scala - Variables - Types ● Mutable ● Immutable
  • 12. Scala Scala - Variables - Types ● Mutable variables are defined using “var” keyword ○ values can be changed ● Immutable variables are defined using “val” keyword ○ values can not be changed after assignment
  • 13. Scala ● val x: Int = 8 // Immutable, Read Only ● var y: Int = 7 // Mutable Scala - Variables - Hands-on
  • 14. Scala What is the importance of immutable variables? ● In large systems, we do not want to be in a situation where a variable's value changes unexpectedly ● In case of threads, APIs, functions and classes, we may not want some of the variables to change Scala - Immutable Variables - Importance
  • 15. Scala ● We can define the variables without specifying their data type ● Scala compiler can understand the type of the variable based on the value assigned to it Scala - Variables - Type Inference
  • 16. Scala ● var x = "hi" // Type Inference (Scala compiler determines the type) ● var x: String = "hi" // Explicitly specifying the type Scala - Variables - Type Inference
  • 17. Scala ● We should always define type of variables explicitly ○ Code will be compiled faster as compiler will not have to spend time in guessing the type ○ No ambiguity Scala - Variables - Type Inference
  • 18. Scala ● A class is a way of creating your own data type ● We can create a data type that represents a customers using a class ● A customer might have states like first name, last name, age, address and contact number ● A customer class might represent behaviours for how these states can be transformed like how to change someone’s address or name ● A class is not concrete until it has been instantiated using a new keyword Scala - Classes
  • 19. Scala class Person(val fname: String, val lname: String, val anage: Int) { val firstname:String = fname; val lastname: String = lname; val age = anage; } val obj = new Person("Robin", "Gill", 42); print(obj.age) print(obj.firstname) Scala - Classes - Hands-on
  • 20. Scala class Person(val fname: String, val lname: String, val anage: Int) { val firstname:String = fname; val lastname: String = lname; val age = anage; def getFullName():String = { return firstname + " " + lastname; } } val obj = new Person("Robin", "Gill", 42); print(obj.getFullName()) Scala - Classes - Methods - Hands-on
  • 21. Scala ● A singleton is a class which can have only one instance at any point in time ● Methods and values that aren’t associated with individual instances of a class belong in singleton objects ● A singleton class can be directly accessed via its name ● Create a singleton class using the keyword object Scala - Singleton Objects
  • 22. Scala object Hello { def message(): String = { return "Hello!!!"; } } Scala - Singleton Objects
  • 23. Scala ● Objects are useful in defining utility methods and constants as they are not related to any specific instance of the class Scala - Singleton Objects
  • 24. Scala 1. def add(x : Int, y : Int) : Int = { return x + y } 2. def add(x : Int, y : Int) = { //return type is inferred x + y //"return" keyword is optional } 3. //Curly braces are optional on single line blocks def add(x : Int, y : Int) = x + y Scala - Functions - Representations
  • 25. Scala ● Collections provide different ways to store data ● Scala collections hierarchy represents a structure of collections that can contain data in different ways Scala - Collections - Overview
  • 27. Scala ● An ordered collection of data ● May or may not be indexed ● Array, List, Vector Scala - Collections - Sequence
  • 28. Scala ● Contains elements of same type ● Fixed size, ordered sequence of data ● Values are contiguous in memory ● Indexed by position Scala - Collections - Sequence - Array
  • 29. Scala ● var languages = Array("Ruby", "SQL", "Python") ● languages(0) ● languages(1) = "C++" ● // Iterate over array for(x <- languages) { println(x); } Scala - Collections - Sequence - Array
  • 30. Scala ● List represents linked list with a value and a pointer to the next element ● Poor performance as data could be anywhere in the memory ● Theoretically unbounded in size Scala - Collections - Sequence - List
  • 31. Scala ● var number_list = List(1, 2, 3) ● number_list :+ 4 Scala - Collections - Sequence - List
  • 32. Scala ● Bag of data with no duplicates ● Order is not guaranteed Scala - Collections - Sets
  • 33. Scala ● var set = Set(76, 5, 9, 1, 2); ● set = set + 9; ● set = set + 20; ● set(5); ● set(14); Scala - Collections - Sets
  • 34. Scala Scala - Collections - Tuples ● Unlike array or list, tuples can hold elements of different data types ● Example var t = (14, 45.69, "Australia") or ● var t = Tuple3(14, 45.69, "Australia") //Same result ● Can be accessed using a 1-based accessor for each value
  • 35. Scala Scala - Collections - Tuples ● t._1 // 14 ● t._3 // Australia ● Can be deconstructed into names bound to each value in the tuple ● Tuples are immutable
  • 36. Scala ● Collection of key/value pairs ● Allows indexing values by a specific key for fast access ● Java HashMap, Python dictionary Scala - Collections - Maps
  • 37. Scala Scala - Collections - Maps ● var colors = Map("red" -> "#FF0000", "yellow" -> "#FFFF00") ● colors("yellow") ● colors += "green" -> "#008000" ● colors -= "red" ● for ((key,value) <- colors) { printf("key: %s, value: %sn", key, value) }
  • 38. Scala Scala - Collections - Maps ● Two types of maps ○ Mutable ○ Immutable ● By default, Scala uses the immutable map ● For mutable maps explicitly import ○ import scala.collection.mutable.Map
  • 39. Scala Scala - Higher Order Functions ● Higher order function is a function which takes another function as an argument ● Describes “how” the work to be done in a collection
  • 40. Scala ● The map applies the function to each value in the collection and returns a new collection Scala - Higher Order Functions - Map
  • 41. Scala Scala - Higher Order Functions - Map 3 13 7 16 3 + 1 7 + 1 16 + 1 13 + 1 4 14 8 17
  • 42. Scala ● var list = List(1,2,3) ● list.map(x => x + 1) // List(2, 3, 4) ● list.map(_+ 1) // Same output Scala - Higher Order Functions - Map
  • 43. Scala ● flatMap takes a function as an argument and this function must return a collection ● Returned collection could be empty ● The flatMap applies the function passed to it as argument on each value in the collection just like map ● The returned collections from each call of function are then merged together to form a new collection Scala - Higher Order Functions - flatMap
  • 44. Scala ● var list = List("Python", "Go") ● list.flatMap(lang => lang + "#") // List(P, y, t, h, o, n, #, G, o, #) ● list.flatMap(_+ "#") // Same output Scala - Higher Order Functions - flatMap
  • 45. Scala ● Filter applies a function to each value in the collection and returns a new collection with values that satisfy a condition specified in the function Scala - Higher Order Functions - Filter
  • 46. Scala Scala - Higher Order Functions - Filter ● var list = List("Scala", "R", "Python", "Go", "SQL") ● list.filter(lang => lang.contains("S")) // List(Scala, SQL)
  • 47. Scala ● Each of the previous higher order functions returned a new collection after applying the transformation ● At times we do not want the functions to return a new collection ○ Waste of memory resources on JVM if we do not want a return value ● foreach applies a function to each value of collection without returning a new collection Scala - Higher Order Functions - foreach
  • 48. Scala ● var list = List("Python", "Go") ● list.foreach(println) Scala - Higher Order Functions - foreach
  • 49. Scala Scala - Higher Order Functions - Reduce
  • 50. Scala Scala - Higher Order Functions - Reduce 3 7 13 16 10 23 39
  • 51. Scala Scala - Higher Order Functions - Reduce ● In previous example, addition of two variables was called again and again until all the values got reduced to a single value ● Please note, in case of reduce input collection should contain elements of same data type
  • 52. Scala Scala - Higher Order Functions - Reduce ● var list = List(3, 7, 13, 16) ● list.reduce((x, y) => x + y) // 39 ● list.reduce(_ + _) // same
  • 53. Scala import java.util.{Date, Locale} import java.text.DateFormat import java.text.DateFormat._ object USDate { def getDate(): String = { val now = new Date val df = getDateInstance(LONG, Locale.US) return df.format(now) } } Scala - Interaction with Java
  • 54. Scala ● If we are working on a big project containing hundreds of source files, it becomes really tedious to compile these files manually ● We need a build tool to manage the compilation of all these files ● SBT is build tool for Scala and Java projects, similar to Java's Maven or ant Scala - Build Tool - SBT
  • 55. Scala ● Sample Scala project is located at CloudxLab GitHub repository https://github.com/singhabhinav/cloudxlab/tree/master/scala/sbt ● Clone the repository git clone https://github.com/singhabhinav/cloudxlab.git ~/cloudxlab ● Or update the repository cd ~/cloudxlab && git pull origin master Scala - Build Tool - SBT - Demo
  • 56. Scala ● cd ~/cloudxlab/scala/sbt ● Look at the build.sbt file and the directory layout. Scala files must be located at src/main/scala ● Run the project using sbt run Scala - Build Tool - SBT - Demo
  • 57. Scala ● Case classes are regular classes that are: ○ Immutable by default ○ Can be pattern matched ○ Compiler automatically generates hashCode and equals methods, so less boilerplate code ○ Helps in writing more expressive and maintainable code Scala - Case Classes
  • 58. Scala ● Sample Scala project is located at CloudxLab GitHub repository https://github.com/singhabhinav/cloudxlab/tree/master/scala/case_cla sses ● Clone the repository git clone https://github.com/singhabhinav/cloudxlab.git ~/cloudxlab ● Or update the repository cd ~/cloudxlab && git pull origin master Scala - Case Classes - Demo
  • 59. Scala ● cd ~/cloudxlab/scala/case_classes ● scala case_class.scala // Run case class demo ● scala pattern_matching.scala // Run pattern matching demo Scala - Case Classes - Demo