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
Ad

More Related Content

What's hot (20)

20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas
shinolajla
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
Martin Odersky
 
Weaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo
Weaving Dataflows with Silk - ScalaMatsuri 2014, TokyoWeaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo
Weaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo
Taro L. Saito
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
Adrian Spender
 
[Start] Scala
[Start] Scala[Start] Scala
[Start] Scala
佑介 九岡
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave Implicit
Martin Odersky
 
Drilling the Async Library
Drilling the Async LibraryDrilling the Async Library
Drilling the Async Library
Knoldus Inc.
 
Logging in Scala
Logging in ScalaLogging in Scala
Logging in Scala
John Nestor
 
What You Need to Know About Lambdas - Jamie Allen (Typesafe)
What You Need to Know About Lambdas - Jamie Allen (Typesafe)What You Need to Know About Lambdas - Jamie Allen (Typesafe)
What You Need to Know About Lambdas - Jamie Allen (Typesafe)
jaxLondonConference
 
flatMap Oslo presentation slides
flatMap Oslo presentation slidesflatMap Oslo presentation slides
flatMap Oslo presentation slides
Martin Odersky
 
Java concurrency questions and answers
Java concurrency questions and answers Java concurrency questions and answers
Java concurrency questions and answers
CodeOps Technologies LLP
 
Networks and Types - the Future of Akka @ ScalaDays NYC 2018
Networks and Types - the Future of Akka @ ScalaDays NYC 2018Networks and Types - the Future of Akka @ ScalaDays NYC 2018
Networks and Types - the Future of Akka @ ScalaDays NYC 2018
Konrad Malawski
 
Scala presentationjune112011
Scala presentationjune112011Scala presentationjune112011
Scala presentationjune112011
PrasannaKumar Sathyanarayanan
 
Understanding Akka Streams, Back Pressure, and Asynchronous Architectures
Understanding Akka Streams, Back Pressure, and Asynchronous ArchitecturesUnderstanding Akka Streams, Back Pressure, and Asynchronous Architectures
Understanding Akka Streams, Back Pressure, and Asynchronous Architectures
Lightbend
 
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIModern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Ganesh Samarthyam
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams
Ganesh Samarthyam
 
PHP, the GraphQL ecosystem and GraphQLite
PHP, the GraphQL ecosystem and GraphQLitePHP, the GraphQL ecosystem and GraphQLite
PHP, the GraphQL ecosystem and GraphQLite
JEAN-GUILLAUME DUJARDIN
 
Introduction to Scala JS
Introduction to Scala JSIntroduction to Scala JS
Introduction to Scala JS
Knoldus Inc.
 
Scala in a wild enterprise
Scala in a wild enterpriseScala in a wild enterprise
Scala in a wild enterprise
Rafael Bagmanov
 
Overview of CoffeeScript
Overview of CoffeeScriptOverview of CoffeeScript
Overview of CoffeeScript
Aniruddha Chakrabarti
 
20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas
shinolajla
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
Martin Odersky
 
Weaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo
Weaving Dataflows with Silk - ScalaMatsuri 2014, TokyoWeaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo
Weaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo
Taro L. Saito
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave Implicit
Martin Odersky
 
Drilling the Async Library
Drilling the Async LibraryDrilling the Async Library
Drilling the Async Library
Knoldus Inc.
 
Logging in Scala
Logging in ScalaLogging in Scala
Logging in Scala
John Nestor
 
What You Need to Know About Lambdas - Jamie Allen (Typesafe)
What You Need to Know About Lambdas - Jamie Allen (Typesafe)What You Need to Know About Lambdas - Jamie Allen (Typesafe)
What You Need to Know About Lambdas - Jamie Allen (Typesafe)
jaxLondonConference
 
flatMap Oslo presentation slides
flatMap Oslo presentation slidesflatMap Oslo presentation slides
flatMap Oslo presentation slides
Martin Odersky
 
Networks and Types - the Future of Akka @ ScalaDays NYC 2018
Networks and Types - the Future of Akka @ ScalaDays NYC 2018Networks and Types - the Future of Akka @ ScalaDays NYC 2018
Networks and Types - the Future of Akka @ ScalaDays NYC 2018
Konrad Malawski
 
Understanding Akka Streams, Back Pressure, and Asynchronous Architectures
Understanding Akka Streams, Back Pressure, and Asynchronous ArchitecturesUnderstanding Akka Streams, Back Pressure, and Asynchronous Architectures
Understanding Akka Streams, Back Pressure, and Asynchronous Architectures
Lightbend
 
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIModern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Ganesh Samarthyam
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams
Ganesh Samarthyam
 
PHP, the GraphQL ecosystem and GraphQLite
PHP, the GraphQL ecosystem and GraphQLitePHP, the GraphQL ecosystem and GraphQLite
PHP, the GraphQL ecosystem and GraphQLite
JEAN-GUILLAUME DUJARDIN
 
Introduction to Scala JS
Introduction to Scala JSIntroduction to Scala JS
Introduction to Scala JS
Knoldus Inc.
 
Scala in a wild enterprise
Scala in a wild enterpriseScala in a wild enterprise
Scala in a wild enterprise
Rafael Bagmanov
 

Similar to Scala final ppt vinay (20)

Quick introduction to scala
Quick introduction to scalaQuick introduction to scala
Quick introduction to scala
Mohammad Hossein Rimaz
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Mohammad Hossein Rimaz
 
Spark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin OderskySpark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin Odersky
Spark Summit
 
Scala Days San Francisco
Scala Days San FranciscoScala Days San Francisco
Scala Days San Francisco
Martin Odersky
 
Develop realtime web with Scala and Xitrum
Develop realtime web with Scala and XitrumDevelop realtime web with Scala and Xitrum
Develop realtime web with Scala and Xitrum
Ngoc Dao
 
Introduction to Scala language
Introduction to Scala languageIntroduction to Scala language
Introduction to Scala language
Aaqib Pervaiz
 
Introducing Scala to your Ruby/Java Shop : My experiences at IGN
Introducing Scala to your Ruby/Java Shop : My experiences at IGNIntroducing Scala to your Ruby/Java Shop : My experiences at IGN
Introducing Scala to your Ruby/Java Shop : My experiences at IGN
Manish Pandit
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
fanf42
 
Introduction to scala for a c programmer
Introduction to scala for a c programmerIntroduction to scala for a c programmer
Introduction to scala for a c programmer
Girish Kumar A L
 
Scala-Ls1
Scala-Ls1Scala-Ls1
Scala-Ls1
Aniket Joshi
 
Scala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on HerokuScala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on Heroku
Havoc Pennington
 
Devoxx
DevoxxDevoxx
Devoxx
Martin Odersky
 
Lecture1
Lecture1Lecture1
Lecture1
Muhammad Fayyaz
 
Intro to Scala
 Intro to Scala Intro to Scala
Intro to Scala
manaswinimysore
 
What`s New in Java 8
What`s New in Java 8What`s New in Java 8
What`s New in Java 8
Mohsen Zainalpour
 
The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at Twitter
Alex Payne
 
Scala and jvm_languages_praveen_technologist
Scala and jvm_languages_praveen_technologistScala and jvm_languages_praveen_technologist
Scala and jvm_languages_praveen_technologist
pmanvi
 
Scala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud Foundry
Pray Desai
 
Rafael Bagmanov «Scala in a wild enterprise»
Rafael Bagmanov «Scala in a wild enterprise»Rafael Bagmanov «Scala in a wild enterprise»
Rafael Bagmanov «Scala in a wild enterprise»
e-Legion
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
Venkateswaran Kandasamy
 
Spark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin OderskySpark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin Odersky
Spark Summit
 
Scala Days San Francisco
Scala Days San FranciscoScala Days San Francisco
Scala Days San Francisco
Martin Odersky
 
Develop realtime web with Scala and Xitrum
Develop realtime web with Scala and XitrumDevelop realtime web with Scala and Xitrum
Develop realtime web with Scala and Xitrum
Ngoc Dao
 
Introduction to Scala language
Introduction to Scala languageIntroduction to Scala language
Introduction to Scala language
Aaqib Pervaiz
 
Introducing Scala to your Ruby/Java Shop : My experiences at IGN
Introducing Scala to your Ruby/Java Shop : My experiences at IGNIntroducing Scala to your Ruby/Java Shop : My experiences at IGN
Introducing Scala to your Ruby/Java Shop : My experiences at IGN
Manish Pandit
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
fanf42
 
Introduction to scala for a c programmer
Introduction to scala for a c programmerIntroduction to scala for a c programmer
Introduction to scala for a c programmer
Girish Kumar A L
 
Scala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on HerokuScala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on Heroku
Havoc Pennington
 
The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at Twitter
Alex Payne
 
Scala and jvm_languages_praveen_technologist
Scala and jvm_languages_praveen_technologistScala and jvm_languages_praveen_technologist
Scala and jvm_languages_praveen_technologist
pmanvi
 
Scala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud Foundry
Pray Desai
 
Rafael Bagmanov «Scala in a wild enterprise»
Rafael Bagmanov «Scala in a wild enterprise»Rafael Bagmanov «Scala in a wild enterprise»
Rafael Bagmanov «Scala in a wild enterprise»
e-Legion
 
Ad

Recently uploaded (20)

Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New VersionPixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
saimabibi60507
 
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMeet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Maxim Salnikov
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
Landscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature ReviewLandscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature Review
Hironori Washizaki
 
Automation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath CertificateAutomation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath Certificate
VICTOR MAESTRE RAMIREZ
 
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
University of Hawai‘i at Mānoa
 
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
Egor Kaleynik
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
Not So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java WebinarNot So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java Webinar
Tier1 app
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
Top 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docxTop 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docx
Portli
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Maxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINKMaxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINK
younisnoman75
 
EASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License CodeEASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License Code
aneelaramzan63
 
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
AxisTechnolabs
 
Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025
kashifyounis067
 
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Dele Amefo
 
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New VersionPixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
saimabibi60507
 
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMeet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Maxim Salnikov
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
Landscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature ReviewLandscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature Review
Hironori Washizaki
 
Automation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath CertificateAutomation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath Certificate
VICTOR MAESTRE RAMIREZ
 
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
University of Hawai‘i at Mānoa
 
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
Egor Kaleynik
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
Not So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java WebinarNot So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java Webinar
Tier1 app
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
Top 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docxTop 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docx
Portli
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Maxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINKMaxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINK
younisnoman75
 
EASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License CodeEASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License Code
aneelaramzan63
 
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
AxisTechnolabs
 
Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025
kashifyounis067
 
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Dele Amefo
 
Ad

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. ????????????