SlideShare a Scribd company logo
Introduction to
VINAY PORWAL
2013UCS032
Table of Contents
• Introduction
• Getting Started
• Features of Language
• Programming Environment
• Demo (Word Count with Spark, Simple Web App using Play, MongoDB,
ReactiveMongo)
• Resources
• Q&A 1
Introduction
2
•Object oriented and functional
•Statically typed - advanced type system
•Compiled to JVM bytecode
but also to CLR, and to JavaScript (in progress)
•High performance
•Very good interoperability with Java
•Support for modularity and extensibility
DSL friendly
History
3
The design of Scala started in 2001 at the (EPFL) by Martin
Odersky. Odersky formerly worked on Generic Java, and javac, Sun's
Java compiler.
May 2011, Odersky
launched Typesafe Inc.
Currently named
Lightbend Inc.
4
Why Scala
5
“Scala is an acronym for
Scalable Language ”
Is so named because it was designed to grow with the demands of its users.
6
Why a new Language?
The work on Scala was motivated
by two hypotheses:
Hypothesis 1: A general-purpose
language needs to be scalable; the
same concepts should describe
small as well as large parts.
Hypothesis 2: Scalability can be
achieved by unifying and
generalizing functional and object-
oriented programming concepts.
If we were forced to name just one aspect of Scala that helps scalability, we’d
pick its combination of object-oriented and functional programming.
7
What is Scala?
• Scala compiles to Byte Code in the JVM. Scala programs compile to JVM
bytecodes.Their run-time performance is usually on par with Java programs.
• You can write a .class being java or scala code.
• Interoperability with Java, So you can easily use the Java Ecosystem.
8
Why Scala?
• Scala is concise. No boilerplate code! (semicolons, return, getter/setter, …)
Fewer lines of code mean not only less typing, but also less effort at reading
and understanding programs and fewer possibilities of defects
• Scala is high-level. OOP and FP let you write more complex programs.
• Scala is statically typed, verbosity is avoided through type inference so it look
likes it’s a dynamic language but it’s not.
9
JVM LanguagesTimeline
10
Indeed Scala JobTrend
11
“
”
Even Apple needs Scala developer
12
If I were to pick a language to use today
other than Java, it would be Scala.
James Gosling, the creator of the Java programming language
“
”
13
Scala Use Cases
• Big Data and Data Science
• Web Application Development, REST API Development
• Distributed System, Concurrency and Parallelism
• Scientific Computation like NLP, Numerical Computing and Data
Visualization
14
They all use Scala
https://www.lightbend.com/resources/case-studies-and-storie 15
We’ve found that Scala has enabled us
to deliver things faster with less code.
GrahamTackley from TheGuardian.
“
”
16
Features of Language
• Scala Language Design
• The Basics of Scala
• Functional Programming in Scala
• Object-Oriented Programming in Scala
17
Scala Language Design
• ScalaType System
• Everything is an Expression
• Lexical scope
• Scopes
18
ScalaType System
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 has a unified type system, enclosed by the type Any at the top of the
hierarchy and the type Nothing at the
bottom of the hierarchy
19
ScalaType System
20
ScalaType System
• Null: Its aTrait.
• null: Its an instance of Null- Similar to Java null.
• Nil: Represents an empty List of anything of zero length. Its
not that it refers to nothing but it refers to List which has no
contents.
• Nothing: is aTrait. Its a subtype of everything. But not
superclass of anything.There are no instances of Nothing.
• None: Used to represent a sensible return value. Just to avoid
null pointer exception. Option has exactly 2 subclasses- Some
and None. None signifies no result from the method.
• Unit: Type of method that doesn’t return a value of anys sort. 21
Everything is An Expression
In programming language terminology, an "expression" is a combination of values and functions
that are combined and interpreted by the compiler to create a new value, as opposed to a
"statement" which is just a standalone unit of execution and doesn't return anything
def ifThenElseExpression(aBool:Boolean) = if aBool then 42 else 0
22
Lexical Scope (Static)
• Scala using Lexical scoping like many other languages
(why?)
• Much easier for the user (programmer)
• Much easier for the compiler to optimize
23
Scopes
In a Scala program, an inner variable is said to shadow a like-named outer variable, because
the outer variable becomes invisible in the inner scope.
𝐿𝑜𝑐𝑎𝑙 𝐷𝑒𝑓𝑖𝑛𝑖𝑡𝑖𝑜𝑛𝑠 → 𝐸𝑥𝑝𝑙𝑖𝑐𝑖𝑡𝑠 𝑖𝑚𝑝𝑜𝑟𝑡𝑠 → 𝑊𝑖𝑙𝑑 𝑐𝑎𝑟𝑑 𝑖𝑚𝑝𝑜𝑟𝑡𝑠 → 𝑃𝑎𝑐𝑘𝑎𝑔𝑒𝑠
24
The Basics of Language
• DataTypes
• Casting
• Opperations
• If Expression
• Arrays &Tuples & Lists
• For & while Comprehension
• Functions
• Call By ...
• Pattern Matching
25
DataTypes
• Byte
• Short
• Int
• Long
• Float
• Double
• Char
• Boolean
• Unit
scala> var a:Int=2
a: Int = 2
scala> var a:Double=2.2
a: Double = 2.2
scala> var a:Float=2.2f
a: Float = 2.2
scala> var a:Byte=4
a: Byte = 4
scala> var a:Boolean=false
a: Boolean = false 26
Casting
• asInstanceOf
scala> var a:Char=(Char)955//Compile error
<console>:1: error: ';' expected but integer literal found.
var a:Char=(Char)955//Compile error
^
scala> var a:Int=955
a: Int = 955
scala> var b=a.asInstanceOf[Char]
b: Char = λ
27
Operations
scala> var a=955
a: Int = 955
scala> import scala.math._
import scala.math._
scala> print(4-3/5.0)
//compile time they will change to primitive not object any more to run faster 3.4
scala> print(a+3)//a.add(3) add=>+
958
scala> println(math.sin(4*Pi/3).abs)
//1)you can import classes 2)=>math.abs(math.sin(4*Pi/3))
0.8660254037844385
scala> if(a==955) | print("lambda")
Lambda
scala> println("HOLY".>=("EVIL"))
true
28
If Expression
scala> var m="wood"
m: String = wood
scala> println(m.length())
4
scala> println(s"$m is brown")
wood is brown
scala> println(f"$m%5s")
wood
scala> if(m=="wood"){//== is equivalent to equal
| print("brown");
| }else if(m.equals("grass")){
| println("green");
| }else{
| print("i don't know")
| }
brown
29
Arrays
scala> var arr=Array(5,4,47,7,8,7)
arr: Array[Int] = Array(5, 4, 47, 7, 8, 7)
scala> println(arr(1));println(arr(2));println(arr(3));
4 47 7
scala> var array=new Array[String](3);
array: Array[String] = Array(null, null, null)
scala> var at=Array(4,4.7,"Gasai Yuno")
at: Array[Any] = Array(4, 4.7, Gasai Yuno)
scala> var matrix=Array.ofDim[Int](2,2)
matrix: Array[Array[Int]] = Array(Array(0, 0), Array(0, 0))
30
Tuples
scala> var tuples=(2*5,"ten",10.0d,10.0f,10.0,(9,"NINE"))
tuples: (Int, String, Double, Float, Double, (Int, String)) =
(10,ten,10.0,10.0,10.0,(9,NINE))
scala> print(tuples._1)
10
scala> print(tuples._2)
ten
scala> print(tuples._6._2)
NINE
31
Lists
scala> var lst=List("b","c","d")
lst: List[String] = List(b, c, d)
scala> print(lst.head)
b
scala> print(lst.tail)
List(c, d)
scala> var lst2="a"::lst
lst2: List[String] = List(a, b, c, d)
scala> var l=1::2::3::4::Nil
l: List[Int] = List(1, 2, 3, 4)
scala> var l2=l::List(5,6)
l2: List[Any] = List(List(1, 2, 3, 4), 5, 6)
scala> var l3=l:::List(5,6)
l3: List[Int] = List(1, 2, 3, 4, 5, 6)
32
While
• while (Boolean Expression) { Expression }
• do { Expression } while (Boolean Expression)
scala> var i=0;
i: Int = 0
scala> while(i<10){
| i+=1;
| print(i+" ")
| }
1 2 3 4 5 6 7 8 9 10
Note : In functional , It is preferred to not use while and in general imperative style.
33
For Comprehension
• for (Iterations and Conditions)
val books = List("Beginning Scala", "Beginning Groovy",
"Beginning Java", "Scala in easy steps", "Scala in 24
hours")
for (book<-books)
println(book)
var scalabooks = for{ book <-books if
book.contains("Scala") }yield book
for(book<-books if book.contains("Scala") )
println(book)
34
foreach
 foreach (Conditions)
scala> val list = List("Human","Dog","Cat")
list: List[String] = List(Human, Dog, Cat)
scala> list.foreach((s : String) => println(s))
Human
Dog
Cat
scala> list.foreach(s => println(s))
Human
Dog
Cat
scala> list.foreach(println)
Human
Dog
Cat
35
Foreach vs For Comprehension
 Foreach VS for each
scala> for (s<- list) println(s)//it is actually
calling foreach
Human
Dog
Cat
scala> for(s<-list if s.length==3) println(s)
Dog
Cat
scala> list.foreach((s : String) => if(s.length()==3)
println(s))
Dog
Cat
36
Functions
scala> import scala.math._
import scala.math._
scala> def add(x:Int,y:Int):Int = {
| x+y//the last value if you dont specify return
|
| }
add: (x: Int, y: Int)Int
scala> def add(x:Double,y:Double) = x+y
add: (x: Double, y: Double)Double
Note: if you add “return” you need to specify return type else you are
not obligated and one line function no need to bracket.
37
Functions
scala> def printAdd(x:Int,y:Int){// no equal mark no return
| println(x+y)
| }
printAdd: (x: Int, y: Int)Unit
scala> def printAdd(x:Double,y:Double):Unit ={// Unit = void
| println(x+y)
| }
printAdd: (x: Double, y: Double)Unit
38
Functions
scala> def distance1(x1:Double,y1:Double,x2:Double,y2:Double):Double={
| def dif(x1:Double,x2:Double)={
| pow(x2-x1,2)
| }
| return sqrt(dif(x1,x2)+dif(y1,y2))
| }
distance1: (x1: Double, y1: Double, x2: Double, y2: Double)Double
scala> def
distance2(x1:Double,y1:Double,x2:Double,y2:Double,dif:(Double,Double)=>Double):Double={
| return sqrt(dif(x1,x2)+dif(y1,y2))
| }
distance2: (x1: Double, y1: Double, x2: Double, y2: Double, dif: (Double, Double) =>
Double)Double
39
Functions
scala> println(add(4.7,3.2))
7.9
scala> println(distance1(0, 0, 3, 0))
3.0
scala> var dif:(Double,Double)=>Double=(x:Double,y:Double)=>{pow(x-y,2)}
dif: (Double, Double) => Double = <function2>
scala> println(distance2(0, 0, 3, 0, dif))//unanonymous
3.0
scala> println(distance2(0, 0, 3, 0, (x:Double,y:Double)=>pow(x-y,2)))//anonymous
3.0
40
Tail Recursion
import scala.annotation.tailrec
// 1 - basic recursive factorial method
def factorial(n: Int): Int = {
if (n == 0) 1 else n * factorial(n-1)
}
// 2 - tail-recursive factorial method
def factorial2(n: Long): Long = {
@tailrec
def factorialAccumulator(acc: Long, n: Long): Long = {
if (n == 0) acc else factorialAccumulator(n*acc, n-1)
}
factorialAccumulator(1, n)
}
41
Call By Name
def delayed(t:=> Long) = {
println("Indelayed method")
println("Param:"+t)
t
}
42
Call By Ref
def notDelayed(t:Long) = {
println("Innotdelayed method")
println("Param:"+t)
t
}
Note : In Java, all method invocations are call-by-reference or call-
by-value (for primitive types) .
Scala gives you an additional mechanism for passing parameters to
methods (and functions):
call-by-name, which passes a code block to the callee. Each time the
callee accesses the parameter, the code
block is executed and the value is calculated. Call-by-name allows you
to pass parameters that might take a
longtime to calculate but may not be used. 43
Pattern Matching
scala> def matchChecking(a:Any):Unit={
| a match{
| case a:Int => {
| println("One");
| "ali"*5;
| }
| case "two" | "One" => {
| println("Two");
| 2*8;
| }
| case a if a<4.7 =>{
| println("four point seven");
| 3.8*2;
| }
| case _ => {
| println("Recognizing ...");
| a;
| }}}
matchChecking: (a: Any)Unit
scala> matchChecking(1);
One
44
Pattern Matching
scala> def simple_fun(list: List[Char]): List[Nothing] =
list match {
| case x :: xs => {
| println(x)
| simple_fun(xs)
| }
| case _ => Nil
| } simple_fun: (list: List[Char])List[Nothing]
scala> simple_fun(simplelist)
a
b
c
d
res22: List[Nothing] = List()
45
Functional Programming in Scala
• Lazy val & Eager Evaluation
• Currying
• Concurrency
• Closures
46
Lazy val & Eager Evaluation
 lazy val vs. val
The difference between them is, that a val is executed when it is
defined whereas a lazy val is executed when it is accessed the first
time.
In contrast to a method (defined with def) a lazy val is executed once
and then never again.This can be useful when an operation takes
long time to complete and when it is not sure if it is later used.
languages (like Scala) are strict by default, but lazy if explicitly
specified for given variables or parameters.
47
Currying
Methods may define multiple parameter lists.When a method is called
with a fewer number of parameter lists, then this will yield a function
taking the missing parameter lists as its arguments.
scala> def nDividesM(m : Int)(n : Int) = (n % m == 0)
nDividesM: (m: Int)(n: Int)Boolean
scala> val isEven = nDividesM(2)_
isEven: Int => Boolean = <function1>
scala> println(isEven(4))
true
Note : when you give only a subset of the parameters to the function,
the result of the expression is a partially applied function.
48
Closures
A closure is a function, whose return value depends on the value of
one or more variables declared outside this function.
scala> var votingAge = 18
votingAge: Int = 18
scala> val isVotingAge = (age: Int) => age >= votingAge
isVotingAge: Int => Boolean = <function1>
scala> isVotingAge(16)
res2: Boolean = false
49
Concurrency
• You have three options in concurrent programming:
• Akka Actor Model
• Thread
• Apache Spark
50
Actor
• Concurrency using threads is hard
• Shared state – locks, race conditions, deadlocks
• Solution – message passing + no shared state
• Inspired by Erlang language
• Erlang used at Ericsson since 1987, open source since
1998
• Facebook chat backend runs on Erlang
51
What is an Actor?
• Actor is an object that receives messages
• Actor has a mailbox – queue of incoming messages
• Message send is by default asynchronous
• Sending a message to an actor immediately returns
52
Object-Oriented Programming in Scala
• Classes
• Objects
• Traits
• Case Classes
• Exceptions
53
Classes
/** A Person class.
* Constructor parameters become
* public members of the class.*/
class Person(val name: String, var age: Int) {}
var p = new Person(“Peter", 21);
p.age += 1;
54
Objects
• Scala’s way for “statics”
• not quite – see next slide
• (in Scala, there is no static keyword)
• “Companion object” for a class
• = object with same name as the class
55
Objects
// we declare singleton object "Person"
// this is a companion object of class Person
object Person {
def defaultName() = "nobody"
}
class Person(val name: String, var age: Int) {
def getName() : String = name
}
// surprise, Person is really an object
val singleton = Person;
var p:Person=new Person(" ",0)
56
Case Classes
Implicitely override toString, equals, hashCode
take object’s structure into account
Usefull in pattern matching
abstract class Expr
case class Number(n: Int) extends Expr
case class Sum(e1: Expr, e2: Expr) extends Expr
// true thanks to overriden equals
Sum(Number(1), Number(2)) ==
Sum(Number(1), Number(2)) 57
Exceptions
object Main {
def main(args: Array[String]) {
try {
val elems = args.map(Integer.parseInt)
println("Sum is: " + elems.foldRight(0) (_ + _)) }
catch {
case e: NumberFormatException =>
println("Usage: scala Main <n1> <n2> ... ")
}
}
}
58
Traits
Like Java interfaces
But can contain implementations and fields
trait Pet {
var age: Int = 0
def greet(): String = {
return "Hi"
}
}
59
ExtendingTraits
class Dog extends Pet {
override def greet() = "Woof"
}
trait ExclamatoryGreeter extends Pet {
override def greet() = super.greet() + " !"
}
60
Mixins traits
Traits can be “mixed in” at instation time
trait ExclamatoryGreeter extends Pet {
override def greet() = super.greet() +
" !"
}
val pet = new Dog with ExclamatoryGreeter
println(pet.greet()) // Woof !
61
Scala has Multiple inheritance!!!
Solving the Diamond Problem
Scala’s solution to the Diamond Problem is actually fairly simple: it
considers the order in which traits are inherited. If there are multiple
implementors of a given member, the implementation in the supertype
that is furthest to the right (in the list of supertypes) “wins.” Of course, the
body of the class or trait doing the inheriting is further to the right than the
entire list of supertypes, so it “wins” all conflicts, should it provide an
overriding implementation for a member
62
Programming Environment
1. Download & Install JDK
2. Download & Install Scala http://www.scala-lang.org/download/.
3. Add the installed software to your environment
4. Type scala in Console
5. Have fun 
Note:You can download plugins in eclipse and intel and code 63
Resources
• http://www.scala-lang.org/files/archive/spec/2.12/
• https://www.tutorialspoint.com/scala/
• http://stackoverflow.com/tags/scala/info
• Beginning Scala
64
THANKS FORYOUR ATTENTION
65

More Related Content

PDF
Scala : language of the future
PDF
Martin Odersky - Evolution of Scala
PPTX
Introduction to Scala
PDF
ITSubbotik - как скрестить ежа с ужом или подводные камни внедрения функциона...
PDF
Preparing for Scala 3
PPTX
Scala - The Simple Parts, SFScala presentation
PDF
What To Leave Implicit
PPTX
A Brief Intro to Scala
Scala : language of the future
Martin Odersky - Evolution of Scala
Introduction to Scala
ITSubbotik - как скрестить ежа с ужом или подводные камни внедрения функциона...
Preparing for Scala 3
Scala - The Simple Parts, SFScala presentation
What To Leave Implicit
A Brief Intro to Scala

What's hot (20)

PDF
20160520 what youneedtoknowaboutlambdas
PPT
Scala Talk at FOSDEM 2009
PDF
Weaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo
KEY
Scala Introduction
PDF
[Start] Scala
PPTX
What To Leave Implicit
ODP
Drilling the Async Library
PDF
Logging in Scala
PDF
What You Need to Know About Lambdas - Jamie Allen (Typesafe)
PPTX
flatMap Oslo presentation slides
PPTX
Java concurrency questions and answers
PDF
Networks and Types - the Future of Akka @ ScalaDays NYC 2018
PPT
Scala presentationjune112011
PDF
Understanding Akka Streams, Back Pressure, and Asynchronous Architectures
PDF
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
PDF
Productive Programming in Java 8 - with Lambdas and Streams
PDF
PHP, the GraphQL ecosystem and GraphQLite
ODP
Introduction to Scala JS
PDF
Scala in a wild enterprise
PPTX
Overview of CoffeeScript
20160520 what youneedtoknowaboutlambdas
Scala Talk at FOSDEM 2009
Weaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo
Scala Introduction
[Start] Scala
What To Leave Implicit
Drilling the Async Library
Logging in Scala
What You Need to Know About Lambdas - Jamie Allen (Typesafe)
flatMap Oslo presentation slides
Java concurrency questions and answers
Networks and Types - the Future of Akka @ ScalaDays NYC 2018
Scala presentationjune112011
Understanding Akka Streams, Back Pressure, and Asynchronous Architectures
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Productive Programming in Java 8 - with Lambdas and Streams
PHP, the GraphQL ecosystem and GraphQLite
Introduction to Scala JS
Scala in a wild enterprise
Overview of CoffeeScript
Ad

Similar to Scala final ppt vinay (20)

PDF
Quick introduction to scala
PPTX
Introduction to Scala
PPTX
Spark - The Ultimate Scala Collections by Martin Odersky
PPT
Scala Days San Francisco
PDF
Develop realtime web with Scala and Xitrum
PPTX
Introduction to Scala language
PPT
Introducing Scala to your Ruby/Java Shop : My experiences at IGN
ODP
A Tour Of Scala
PPTX
Introduction to scala for a c programmer
PPTX
Scala-Ls1
PDF
Scala, Akka, and Play: An Introduction on Heroku
PPT
PDF
Lecture1
PPTX
Intro to Scala
PPTX
What`s New in Java 8
KEY
The Why and How of Scala at Twitter
PDF
Scala and jvm_languages_praveen_technologist
PPTX
Scala, Play 2.0 & Cloud Foundry
PDF
Rafael Bagmanov «Scala in a wild enterprise»
PPT
Scala in a nutshell by venkat
Quick introduction to scala
Introduction to Scala
Spark - The Ultimate Scala Collections by Martin Odersky
Scala Days San Francisco
Develop realtime web with Scala and Xitrum
Introduction to Scala language
Introducing Scala to your Ruby/Java Shop : My experiences at IGN
A Tour Of Scala
Introduction to scala for a c programmer
Scala-Ls1
Scala, Akka, and Play: An Introduction on Heroku
Lecture1
Intro to Scala
What`s New in Java 8
The Why and How of Scala at Twitter
Scala and jvm_languages_praveen_technologist
Scala, Play 2.0 & Cloud Foundry
Rafael Bagmanov «Scala in a wild enterprise»
Scala in a nutshell by venkat
Ad

Recently uploaded (20)

PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PPTX
L1 - Introduction to python Backend.pptx
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
AI in Product Development-omnex systems
PDF
Digital Strategies for Manufacturing Companies
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
System and Network Administration Chapter 2
PPTX
Reimagine Home Health with the Power of Agentic AI​
PPTX
ai tools demonstartion for schools and inter college
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
Design an Analysis of Algorithms II-SECS-1021-03
VVF-Customer-Presentation2025-Ver1.9.pptx
L1 - Introduction to python Backend.pptx
How to Migrate SBCGlobal Email to Yahoo Easily
Softaken Excel to vCard Converter Software.pdf
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Upgrade and Innovation Strategies for SAP ERP Customers
PTS Company Brochure 2025 (1).pdf.......
AI in Product Development-omnex systems
Digital Strategies for Manufacturing Companies
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
wealthsignaloriginal-com-DS-text-... (1).pdf
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Internet Downloader Manager (IDM) Crack 6.42 Build 41
System and Network Administration Chapter 2
Reimagine Home Health with the Power of Agentic AI​
ai tools demonstartion for schools and inter college
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Design an Analysis of Algorithms I-SECS-1021-03
Design an Analysis of Algorithms II-SECS-1021-03

Scala final ppt vinay

  • 2. Table of Contents • Introduction • Getting Started • Features of Language • Programming Environment • Demo (Word Count with Spark, Simple Web App using Play, MongoDB, ReactiveMongo) • Resources • Q&A 1
  • 3. Introduction 2 •Object oriented and functional •Statically typed - advanced type system •Compiled to JVM bytecode but also to CLR, and to JavaScript (in progress) •High performance •Very good interoperability with Java •Support for modularity and extensibility DSL friendly
  • 4. History 3 The design of Scala started in 2001 at the (EPFL) by Martin Odersky. Odersky formerly worked on Generic Java, and javac, Sun's Java compiler.
  • 5. May 2011, Odersky launched Typesafe Inc. Currently named Lightbend Inc. 4
  • 7. “Scala is an acronym for Scalable Language ” Is so named because it was designed to grow with the demands of its users. 6
  • 8. Why a new Language? The work on Scala was motivated by two hypotheses: Hypothesis 1: A general-purpose language needs to be scalable; the same concepts should describe small as well as large parts. Hypothesis 2: Scalability can be achieved by unifying and generalizing functional and object- oriented programming concepts. If we were forced to name just one aspect of Scala that helps scalability, we’d pick its combination of object-oriented and functional programming. 7
  • 9. What is Scala? • Scala compiles to Byte Code in the JVM. Scala programs compile to JVM bytecodes.Their run-time performance is usually on par with Java programs. • You can write a .class being java or scala code. • Interoperability with Java, So you can easily use the Java Ecosystem. 8
  • 10. Why Scala? • Scala is concise. No boilerplate code! (semicolons, return, getter/setter, …) Fewer lines of code mean not only less typing, but also less effort at reading and understanding programs and fewer possibilities of defects • Scala is high-level. OOP and FP let you write more complex programs. • Scala is statically typed, verbosity is avoided through type inference so it look likes it’s a dynamic language but it’s not. 9
  • 13. “ ” Even Apple needs Scala developer 12
  • 14. If I were to pick a language to use today other than Java, it would be Scala. James Gosling, the creator of the Java programming language “ ” 13
  • 15. Scala Use Cases • Big Data and Data Science • Web Application Development, REST API Development • Distributed System, Concurrency and Parallelism • Scientific Computation like NLP, Numerical Computing and Data Visualization 14
  • 16. They all use Scala https://www.lightbend.com/resources/case-studies-and-storie 15
  • 17. We’ve found that Scala has enabled us to deliver things faster with less code. GrahamTackley from TheGuardian. “ ” 16
  • 18. Features of Language • Scala Language Design • The Basics of Scala • Functional Programming in Scala • Object-Oriented Programming in Scala 17
  • 19. Scala Language Design • ScalaType System • Everything is an Expression • Lexical scope • Scopes 18
  • 20. ScalaType System 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 has a unified type system, enclosed by the type Any at the top of the hierarchy and the type Nothing at the bottom of the hierarchy 19
  • 22. ScalaType System • Null: Its aTrait. • null: Its an instance of Null- Similar to Java null. • Nil: Represents an empty List of anything of zero length. Its not that it refers to nothing but it refers to List which has no contents. • Nothing: is aTrait. Its a subtype of everything. But not superclass of anything.There are no instances of Nothing. • None: Used to represent a sensible return value. Just to avoid null pointer exception. Option has exactly 2 subclasses- Some and None. None signifies no result from the method. • Unit: Type of method that doesn’t return a value of anys sort. 21
  • 23. Everything is An Expression In programming language terminology, an "expression" is a combination of values and functions that are combined and interpreted by the compiler to create a new value, as opposed to a "statement" which is just a standalone unit of execution and doesn't return anything def ifThenElseExpression(aBool:Boolean) = if aBool then 42 else 0 22
  • 24. Lexical Scope (Static) • Scala using Lexical scoping like many other languages (why?) • Much easier for the user (programmer) • Much easier for the compiler to optimize 23
  • 25. Scopes In a Scala program, an inner variable is said to shadow a like-named outer variable, because the outer variable becomes invisible in the inner scope. 𝐿𝑜𝑐𝑎𝑙 𝐷𝑒𝑓𝑖𝑛𝑖𝑡𝑖𝑜𝑛𝑠 → 𝐸𝑥𝑝𝑙𝑖𝑐𝑖𝑡𝑠 𝑖𝑚𝑝𝑜𝑟𝑡𝑠 → 𝑊𝑖𝑙𝑑 𝑐𝑎𝑟𝑑 𝑖𝑚𝑝𝑜𝑟𝑡𝑠 → 𝑃𝑎𝑐𝑘𝑎𝑔𝑒𝑠 24
  • 26. The Basics of Language • DataTypes • Casting • Opperations • If Expression • Arrays &Tuples & Lists • For & while Comprehension • Functions • Call By ... • Pattern Matching 25
  • 27. DataTypes • Byte • Short • Int • Long • Float • Double • Char • Boolean • Unit scala> var a:Int=2 a: Int = 2 scala> var a:Double=2.2 a: Double = 2.2 scala> var a:Float=2.2f a: Float = 2.2 scala> var a:Byte=4 a: Byte = 4 scala> var a:Boolean=false a: Boolean = false 26
  • 28. Casting • asInstanceOf scala> var a:Char=(Char)955//Compile error <console>:1: error: ';' expected but integer literal found. var a:Char=(Char)955//Compile error ^ scala> var a:Int=955 a: Int = 955 scala> var b=a.asInstanceOf[Char] b: Char = λ 27
  • 29. Operations scala> var a=955 a: Int = 955 scala> import scala.math._ import scala.math._ scala> print(4-3/5.0) //compile time they will change to primitive not object any more to run faster 3.4 scala> print(a+3)//a.add(3) add=>+ 958 scala> println(math.sin(4*Pi/3).abs) //1)you can import classes 2)=>math.abs(math.sin(4*Pi/3)) 0.8660254037844385 scala> if(a==955) | print("lambda") Lambda scala> println("HOLY".>=("EVIL")) true 28
  • 30. If Expression scala> var m="wood" m: String = wood scala> println(m.length()) 4 scala> println(s"$m is brown") wood is brown scala> println(f"$m%5s") wood scala> if(m=="wood"){//== is equivalent to equal | print("brown"); | }else if(m.equals("grass")){ | println("green"); | }else{ | print("i don't know") | } brown 29
  • 31. Arrays scala> var arr=Array(5,4,47,7,8,7) arr: Array[Int] = Array(5, 4, 47, 7, 8, 7) scala> println(arr(1));println(arr(2));println(arr(3)); 4 47 7 scala> var array=new Array[String](3); array: Array[String] = Array(null, null, null) scala> var at=Array(4,4.7,"Gasai Yuno") at: Array[Any] = Array(4, 4.7, Gasai Yuno) scala> var matrix=Array.ofDim[Int](2,2) matrix: Array[Array[Int]] = Array(Array(0, 0), Array(0, 0)) 30
  • 32. Tuples scala> var tuples=(2*5,"ten",10.0d,10.0f,10.0,(9,"NINE")) tuples: (Int, String, Double, Float, Double, (Int, String)) = (10,ten,10.0,10.0,10.0,(9,NINE)) scala> print(tuples._1) 10 scala> print(tuples._2) ten scala> print(tuples._6._2) NINE 31
  • 33. Lists scala> var lst=List("b","c","d") lst: List[String] = List(b, c, d) scala> print(lst.head) b scala> print(lst.tail) List(c, d) scala> var lst2="a"::lst lst2: List[String] = List(a, b, c, d) scala> var l=1::2::3::4::Nil l: List[Int] = List(1, 2, 3, 4) scala> var l2=l::List(5,6) l2: List[Any] = List(List(1, 2, 3, 4), 5, 6) scala> var l3=l:::List(5,6) l3: List[Int] = List(1, 2, 3, 4, 5, 6) 32
  • 34. While • while (Boolean Expression) { Expression } • do { Expression } while (Boolean Expression) scala> var i=0; i: Int = 0 scala> while(i<10){ | i+=1; | print(i+" ") | } 1 2 3 4 5 6 7 8 9 10 Note : In functional , It is preferred to not use while and in general imperative style. 33
  • 35. For Comprehension • for (Iterations and Conditions) val books = List("Beginning Scala", "Beginning Groovy", "Beginning Java", "Scala in easy steps", "Scala in 24 hours") for (book<-books) println(book) var scalabooks = for{ book <-books if book.contains("Scala") }yield book for(book<-books if book.contains("Scala") ) println(book) 34
  • 36. foreach  foreach (Conditions) scala> val list = List("Human","Dog","Cat") list: List[String] = List(Human, Dog, Cat) scala> list.foreach((s : String) => println(s)) Human Dog Cat scala> list.foreach(s => println(s)) Human Dog Cat scala> list.foreach(println) Human Dog Cat 35
  • 37. Foreach vs For Comprehension  Foreach VS for each scala> for (s<- list) println(s)//it is actually calling foreach Human Dog Cat scala> for(s<-list if s.length==3) println(s) Dog Cat scala> list.foreach((s : String) => if(s.length()==3) println(s)) Dog Cat 36
  • 38. Functions scala> import scala.math._ import scala.math._ scala> def add(x:Int,y:Int):Int = { | x+y//the last value if you dont specify return | | } add: (x: Int, y: Int)Int scala> def add(x:Double,y:Double) = x+y add: (x: Double, y: Double)Double Note: if you add “return” you need to specify return type else you are not obligated and one line function no need to bracket. 37
  • 39. Functions scala> def printAdd(x:Int,y:Int){// no equal mark no return | println(x+y) | } printAdd: (x: Int, y: Int)Unit scala> def printAdd(x:Double,y:Double):Unit ={// Unit = void | println(x+y) | } printAdd: (x: Double, y: Double)Unit 38
  • 40. Functions scala> def distance1(x1:Double,y1:Double,x2:Double,y2:Double):Double={ | def dif(x1:Double,x2:Double)={ | pow(x2-x1,2) | } | return sqrt(dif(x1,x2)+dif(y1,y2)) | } distance1: (x1: Double, y1: Double, x2: Double, y2: Double)Double scala> def distance2(x1:Double,y1:Double,x2:Double,y2:Double,dif:(Double,Double)=>Double):Double={ | return sqrt(dif(x1,x2)+dif(y1,y2)) | } distance2: (x1: Double, y1: Double, x2: Double, y2: Double, dif: (Double, Double) => Double)Double 39
  • 41. Functions scala> println(add(4.7,3.2)) 7.9 scala> println(distance1(0, 0, 3, 0)) 3.0 scala> var dif:(Double,Double)=>Double=(x:Double,y:Double)=>{pow(x-y,2)} dif: (Double, Double) => Double = <function2> scala> println(distance2(0, 0, 3, 0, dif))//unanonymous 3.0 scala> println(distance2(0, 0, 3, 0, (x:Double,y:Double)=>pow(x-y,2)))//anonymous 3.0 40
  • 42. Tail Recursion import scala.annotation.tailrec // 1 - basic recursive factorial method def factorial(n: Int): Int = { if (n == 0) 1 else n * factorial(n-1) } // 2 - tail-recursive factorial method def factorial2(n: Long): Long = { @tailrec def factorialAccumulator(acc: Long, n: Long): Long = { if (n == 0) acc else factorialAccumulator(n*acc, n-1) } factorialAccumulator(1, n) } 41
  • 43. Call By Name def delayed(t:=> Long) = { println("Indelayed method") println("Param:"+t) t } 42
  • 44. Call By Ref def notDelayed(t:Long) = { println("Innotdelayed method") println("Param:"+t) t } Note : In Java, all method invocations are call-by-reference or call- by-value (for primitive types) . Scala gives you an additional mechanism for passing parameters to methods (and functions): call-by-name, which passes a code block to the callee. Each time the callee accesses the parameter, the code block is executed and the value is calculated. Call-by-name allows you to pass parameters that might take a longtime to calculate but may not be used. 43
  • 45. Pattern Matching scala> def matchChecking(a:Any):Unit={ | a match{ | case a:Int => { | println("One"); | "ali"*5; | } | case "two" | "One" => { | println("Two"); | 2*8; | } | case a if a<4.7 =>{ | println("four point seven"); | 3.8*2; | } | case _ => { | println("Recognizing ..."); | a; | }}} matchChecking: (a: Any)Unit scala> matchChecking(1); One 44
  • 46. Pattern Matching scala> def simple_fun(list: List[Char]): List[Nothing] = list match { | case x :: xs => { | println(x) | simple_fun(xs) | } | case _ => Nil | } simple_fun: (list: List[Char])List[Nothing] scala> simple_fun(simplelist) a b c d res22: List[Nothing] = List() 45
  • 47. Functional Programming in Scala • Lazy val & Eager Evaluation • Currying • Concurrency • Closures 46
  • 48. Lazy val & Eager Evaluation  lazy val vs. val The difference between them is, that a val is executed when it is defined whereas a lazy val is executed when it is accessed the first time. In contrast to a method (defined with def) a lazy val is executed once and then never again.This can be useful when an operation takes long time to complete and when it is not sure if it is later used. languages (like Scala) are strict by default, but lazy if explicitly specified for given variables or parameters. 47
  • 49. Currying Methods may define multiple parameter lists.When a method is called with a fewer number of parameter lists, then this will yield a function taking the missing parameter lists as its arguments. scala> def nDividesM(m : Int)(n : Int) = (n % m == 0) nDividesM: (m: Int)(n: Int)Boolean scala> val isEven = nDividesM(2)_ isEven: Int => Boolean = <function1> scala> println(isEven(4)) true Note : when you give only a subset of the parameters to the function, the result of the expression is a partially applied function. 48
  • 50. Closures A closure is a function, whose return value depends on the value of one or more variables declared outside this function. scala> var votingAge = 18 votingAge: Int = 18 scala> val isVotingAge = (age: Int) => age >= votingAge isVotingAge: Int => Boolean = <function1> scala> isVotingAge(16) res2: Boolean = false 49
  • 51. Concurrency • You have three options in concurrent programming: • Akka Actor Model • Thread • Apache Spark 50
  • 52. Actor • Concurrency using threads is hard • Shared state – locks, race conditions, deadlocks • Solution – message passing + no shared state • Inspired by Erlang language • Erlang used at Ericsson since 1987, open source since 1998 • Facebook chat backend runs on Erlang 51
  • 53. What is an Actor? • Actor is an object that receives messages • Actor has a mailbox – queue of incoming messages • Message send is by default asynchronous • Sending a message to an actor immediately returns 52
  • 54. Object-Oriented Programming in Scala • Classes • Objects • Traits • Case Classes • Exceptions 53
  • 55. Classes /** A Person class. * Constructor parameters become * public members of the class.*/ class Person(val name: String, var age: Int) {} var p = new Person(“Peter", 21); p.age += 1; 54
  • 56. Objects • Scala’s way for “statics” • not quite – see next slide • (in Scala, there is no static keyword) • “Companion object” for a class • = object with same name as the class 55
  • 57. Objects // we declare singleton object "Person" // this is a companion object of class Person object Person { def defaultName() = "nobody" } class Person(val name: String, var age: Int) { def getName() : String = name } // surprise, Person is really an object val singleton = Person; var p:Person=new Person(" ",0) 56
  • 58. Case Classes Implicitely override toString, equals, hashCode take object’s structure into account Usefull in pattern matching abstract class Expr case class Number(n: Int) extends Expr case class Sum(e1: Expr, e2: Expr) extends Expr // true thanks to overriden equals Sum(Number(1), Number(2)) == Sum(Number(1), Number(2)) 57
  • 59. Exceptions object Main { def main(args: Array[String]) { try { val elems = args.map(Integer.parseInt) println("Sum is: " + elems.foldRight(0) (_ + _)) } catch { case e: NumberFormatException => println("Usage: scala Main <n1> <n2> ... ") } } } 58
  • 60. Traits Like Java interfaces But can contain implementations and fields trait Pet { var age: Int = 0 def greet(): String = { return "Hi" } } 59
  • 61. ExtendingTraits class Dog extends Pet { override def greet() = "Woof" } trait ExclamatoryGreeter extends Pet { override def greet() = super.greet() + " !" } 60
  • 62. Mixins traits Traits can be “mixed in” at instation time trait ExclamatoryGreeter extends Pet { override def greet() = super.greet() + " !" } val pet = new Dog with ExclamatoryGreeter println(pet.greet()) // Woof ! 61
  • 63. Scala has Multiple inheritance!!! Solving the Diamond Problem Scala’s solution to the Diamond Problem is actually fairly simple: it considers the order in which traits are inherited. If there are multiple implementors of a given member, the implementation in the supertype that is furthest to the right (in the list of supertypes) “wins.” Of course, the body of the class or trait doing the inheriting is further to the right than the entire list of supertypes, so it “wins” all conflicts, should it provide an overriding implementation for a member 62
  • 64. Programming Environment 1. Download & Install JDK 2. Download & Install Scala http://www.scala-lang.org/download/. 3. Add the installed software to your environment 4. Type scala in Console 5. Have fun  Note:You can download plugins in eclipse and intel and code 63

Editor's Notes

  • #6: Criada na Suiça Hoje mantêm o Scala e os frameworks Play e Akka
  • #8: Tem esse nome pq é designada para crescer de acordo com a demanda do usuário. criar linguagens (DSL)
  • #15: “Se eu escolhesse uma língua para usar hoje além de Java, seria Scala”
  • #17: Pizza já tinha: - Generics - Class cases - Pattern matching
  • #18: - Nós descobrimos que Scala nos permitiu entregar as coisas mais rápido, com menos código. - Falar algum fato sobre eles. ????????????