Introductiontoscala 161222153627
Introductiontoscala 161222153627
• History
• Why Scala
• Scala Ecosystem and Use Cases
2
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.
4
Martin decided take some of the ideas from
functional programming and move them into the
Java space. He has created a language
called Pizza.
Currently named
Lightbend Inc.
9
Why Scala
10
“ Scala is an acronym for
Scalable Language ”
Is so named because it was designed to grow with the demands of its users.
11
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.
12
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.
• 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.
14
JVM Languages Timeline
15
Indeed Scala Job Trend
16
Even Apple needs Scala developer
“
”
17
“If I were to pick a language to use today
other than Java, it would be Scala. ”
19
Scala Use Cases
20
Scala Use Cases
• Apache Spark is written in Scala. You can use Spark for machine learning,
graph processing, streaming and generally as an in-memory distributed,
fault-tolerant data processing engine.
21
Scala Use Cases
22
Scala Use Cases
23
Scala Use Cases
24
Scala Use Cases
• Play Framework makes it easy to build web applications with Java & Scala.
25
Scala Use Cases
• Lift claim that it is the most powerful, most secure web framework available
today.
26
Scala Use Cases
27
Scala Use Cases
28
Scala Use Cases
29
Scala Use Cases
Scientific Computation
30
They all use Scala
https://www.lightbend.com/resources/case-studies-and-storie 31
“ We’ve found that Scala has enabled us
to deliver things faster with less code. ”
Graham Tackley from TheGuardian. 32
Features of Language
33
Scala Language Design
34
Scala Type 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
35
Scala Type System
36
Scala Type System
• Null: Its a Trait.
• 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 a Trait. 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. 37
Everything is An Expression
38
Lexical Scope (Static)
39
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.
40
The Basics of Language
• Data Types
• Casting
• Opperations
• If Expression
• Arrays & Tuples & Lists
• For & while Comprehension
• Functions
• Call By ...
• Pattern Matching
41
Data Types
• asInstanceOf
scala> var a:Char=(Char)955//Compile error
<console>:1: error: ';' expected but integer literal found.
var a:Char=(Char)955//Compile error
^
43
Operations
scala> var a=955
a: Int = 955
scala> print(4-3/5.0)
//compile time they will change to primitive not object any more to run faster 3.4
scala> println(math.sin(4*Pi/3).abs)
//1)you can import classes 2)=>math.abs(math.sin(4*Pi/3))
0.8660254037844385
scala> println("HOLY".>=("EVIL")) 44
true
If Expression
scala> var m="wood"
m: String = wood
scala> println(m.length())
4
scala> println(f"$m%5s")
wood
scala> println(arr(1));println(arr(2));println(arr(3));
4 47 7
46
Tuples
scala> print(tuples._1)
10
scala> print(tuples._2)
ten
scala> print(tuples._6._2)
NINE
47
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> 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.
49
For Comprehension
• for (Iterations and Conditions)
for (book<-books)
println(book)
for(book<-books if book.contains("Scala") )
println(book)
50
foreach
foreach (Conditions)
scala> val list = List("Human","Dog","Cat")
list: List[String] = List(Human, Dog, Cat)
Cat
Functions
Note: if you add “return” you need to specify return type else you are 53
not obligated and one line function no need to bracket.
Functions
54
Functions
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
55
Functions
scala> println(add(4.7,3.2))
7.9
58
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. 59
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
60
scala> matchChecking(1);
One
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 61
res22: List[Nothing] = List()
Functional Programming in Scala
62
Lazy val & Eager Evaluation
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.
64
Closures
A closure is a function, whose return value depends on the value of
one or more variables declared outside this function.
scala> isVotingAge(16)
res2: Boolean = false
65
Concurrency
66
Actor
• Concurrency using threads is hard
• Shared state – locks, race conditions, deadlocks
67
What is an Actor?
68
Object-Oriented Programming in Scala
• Classes
• Objects
• Traits
• Case Classes
• Exceptions
69
Classes
/** A Person class.
* Constructor parameters become
* public members of the class.*/
class Person(val name: String, var age: Int) {}
70
Objects
71
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
}
trait Pet {
var age: Int = 0
def greet(): String = {
return "Hi"
}
}
75
Extending Traits
76
Mixins traits
Traits can be “mixed in” at instation time
77
Scala has Multiple inheritance!!!
78
Programming Environment
• http://www.scala-lang.org/files/archive/spec/2.12/
• https://www.tutorialspoint.com/scala/
• http://stackoverflow.com/tags/scala/info
• Beginning Scala
80
Q &A
81
THANKS FOR YOUR ATTENTION
82