SlideShare uma empresa Scribd logo
1 de 60
Baixar para ler offline
@
1
• Introduction
• Basics of Scala Programming Language
• Object-Oriented Programming with Scala
• Functional Programming with Scala
• The Road Ahead
• Q&A
2
3
Is so named because it was designed to grow with the
demands of its users.
4
Scala is an acronym for
Scalable 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.
5
If we were forced to name just one aspect of Scala that helps scalability, we’d pick it
combination of object-oriented and functional programming.
6
Agile, with lightweight syntax
No boilerplate code
Object-Oriented Functional
Safe and Performant, with strong static typing
• 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.
7
• 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.
8
James Gosling, the creator of the Java programming language
9
If I were to pick a language to use
today other than Java, it would be
Scala.
10
• 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
11
• 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.
12
• Apache Kafka is written in Scala and Java. It provides a unified,
high-throughput, low-latency platform for handling real-time
data feeds.
13
• Apache Samza is a distributed stream processing framework written in
Java and Scala. It uses Apache Kafka for messaging, and Apache
Hadoop YARN to provide fault tolerance, processor isolation, security,
and resource management.
14
• Apache Flink is a distributed streaming dataflow engine written in Java
and Scala.
15
• Play is a stateless, asynchronous, and non-blocking framework
that uses an underlying fork-join thread pool to do work stealing
for network operations, and can leverage Akka for user level
operations.
• Play Framework makes it easy to build web applications with Java
& Scala.
16
• Lift claim that it is the most powerful, most secure web
framework available today.
• It’s Secure, Scalable, Modular, Designer friendly, and Developer
centric.
17
• Spray is an open-source toolkit for building REST/HTTP-based
integration layers on top of Scala and Akka.
• Being asynchronous, actor-based, fast, lightweight, modular and
testable it's a great way to connect your Scala applications to the
world.
18
• Scalatra is a simple, accessible and free web micro-framework.
• It combines the power of the JVM with the beauty and brevity of
Scala, helping you quickly build high-performance web sites and
APIs.
19
• Akka is open source middleware for building highly concurrent,
distributed and fault-tolerant systems on the JVM.
• Akka is built with Scala, but offers both Scala and Java APIs to
developers.
• At the heart of Akka is the concept of Actors, which provide an
ideal model for thinking about highly concurrent and scalable
systems.
20
• Scala NLP library including Breeze, Epic, Puck.
• Wisp is a web-based plotting library.
• ADAM is a genomics processing engine and specialized file format built
using Apache Avro, Apache Spark and Parquet.
• Scala-Chart is another library for creating and working with carts.
• Scalalab is an easy and efficient MATLAB-like scientific computing
library in Scala
21
https://www.lightbend.com/resources/case-studies-and-storie
22
23
24
• 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
val name = "KNTU“
> name: String = KNTU
val id = 12L
> id: Long = 12
val pi:Float = 3.14F
> pi: Float = 3.14
25
• Byte
• Short
• Int
• Long
• Float
• Double
• Char
• Boolean
• Unit
26
var a:Int=2
> a: Int = 2
var a:Double=2.2
> a: Double = 2.2
var a:Float=2.2F
> a: Float = 2.2
var a:Byte=4
> a: Byte = 4
var a:Boolean=false
> a: Boolean = false
println(a)
> false res0: Unit = ()
// variable
var name = "foo"
name = "bar"
// value
val age = 18
age = 20
27
• An expression-oriented programming language is a
programming language where every (or nearly every)
construction is an expression and thus yields a value.
• All functional programming languages are expression-oriented.
• As we seen, even “println” has return value of type Unit.
28
val name = "KNTU"
> name: String = KNTU
if(name.length == 1.*(4)) "*" else "#"
> res0: String = *
val name = "Rimaz"
> name: String = Rimaz
if(name.length() == 1 * 4){
"*"
} else{
"#"
}
> res0: String = #
29
var count = 0
while(count < 10) count+=1
var count = 0
do count+=2 while(count<10)
Note: Avoid imperative style of programming like while loops and
mutation, Think Functional.
30
31
val range = 1 to 10
> range: scala.collection.immutable.Range.Inclusive = Range 1 to 10
println(range.last) // 10
val range2 = 1 until 10
> range2: scala.collection.immutable.Range = Range 1 until 10
println(range2.last) // 9
val range3 = 1 until 10 by 3
> range3: scala.collection.immutable.Range = Range 1 until 10 by 3
println(range3.last) // 7
32
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))
print(tuples._1)
> 10
print(tuples._2)
> ten
print(tuples._6._2)
> NINE
33
var lst=List("b","c","d")
> lst: List[String] = List(b, c, d)
print(lst.head)
> b
print(lst.tail)
> List(c, d)
var lst2="a"::lst
> lst2: List[String] = List(a, b, c, d)
var l=1::2::3::4::Nil
> l: List[Int] = List(1, 2, 3, 4)
var l2=l::List(5,6)
> l2: List[Any] = List(List(1, 2, 3, 4), 5, 6)
var l3=l:::List(5,6)
> l3: List[Int] = List(1, 2, 3, 4, 5, 6)
34
var array=new Array[String](3)
> array: Array[String] = Array(null, null, null)
var at=Array(4,4.7,"Gasai Yuno")
> at: Array[Any] = Array(4, 4.7, Gasai Yuno)
val mat = Array.ofDim[Int](3,4)
mat(1)(2) = 3
35
val books = List("Beginning Scala", "Beginning Groovy",
"Beginning Java", "Scala in 24 hours")
for (book<-books) println(book)
var scalabooks =
for{ book <-books if book.contains("Scala") } yield book
> scalabooks: List[String] = List(Beginning Scala, Scala in 24 hours)
for(book<-books if book.contains("Scala") ) println(book)
36
37
import scala.math.{sqrt,pow} //abs is not visible
class Person(val name: String, var age: Int) {}
var p = new Person("Peter", 21)
p.age += 1
class Point(private var x: Double, val y: Double) {
def distanceTo(o:Point) = sqrt(pow(x-o.x,2) + pow(y-o.y,2))
}
var p1 = new Point(3,4) //p1.y += 1, y is value not varibale
var p2 = new Point(3,6)
println(p1.distanceTo(p2)) //2
38
• 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
39
40
// 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
Person.defaultName()
41
Implicitly override toString, equals, hashCode
• take object’s structure into account
• Useful in pattern matching
case class Person(private val name: String, private val age: Int) {}
val p1 = new Person("Hossein",21)
> p1: Person = Person(Hossein,21)
val p2 = Person("Hossein",21)
p1 == p2 //== is equivalent to equals
42
Traits are used to share interfaces and fields between classes.
They are similar to Java 8’s interfaces.
trait Pet {
val name: String
def greet(): String = { return s"Hi, I'm ${name}" }
}
case class Dog(name:String) extends Pet
val dog = Dog("Hachi")
dog.greet()
> res0: String = Hi, I’m Hachi
43
Mixins are a language concept that allows a programmer to inject
some code into a class.
Typically, the mixin will export the desired functionality to a child
class, without creating a rigid, single "is a" relationship.
It provides a mechanism for multiple inheritance by allowing
multiple classes to use the common functionality, but without the
complex semantics of multiple inheritance.
Mixins encourage code reuse and can be used to avoid the
inheritance ambiguity that multiple inheritance can cause (the
"diamond problem")
44
trait Language {
val name:String
override def toString = name
}
trait JVM { override def toString = super.toString+" runs on JVM" }
trait Static { override def toString = super.toString+" is Static" }
class Scala extends Language with JVM with Static {
val name = "Scala"
}
println(new Scala)
// Scala runs on JVM is Static
45
• First-class functions
- Functions as variables, method parameters, and return value
• Pure functions
- No side effect
• Recursion
• Immutable variables
• Non-Strict evaluation
- Delay evaluation until the last moment
• Statements
- Expression-Oriented
• Pattern matching
46
def fibo(n:Int) : Int = if(n<2) n else fibo(n-1) + fibo(n-2)
> fibo: fibo[](val n: Int) => Int
for( i <- 0 to 10) yield fibo(i)
> res0: res0: scala.collection.immutable.IndexedSeq[Int]
= Vector(0, 1, 1, 2, 3, 5, 8, 13)
47
def func(x:Int,y:Int, z:(Int,Int)=>Int): Int = z.apply(x,y)
func(2,3,(x,y)=> x*y)
val adder = (x:Int,y:Int)=> x+y
func(2,3,adder)
func(2,3,(x,y)=> (x*x-y*y).abs)
48
var offset = 1
val plusOffset = (x:Int) => x + offset
plusOffset(5) // 6
foo = 5
plusOffset(5) // 10
A Closure is a function, whose return value depends on the value
of one or more variables declared outside this function.
49
50
Tail Recursive function is a function calls itself as its final
operation. A Tail Recursive Function can automatically optimized
by compiler to avoid Stack Overflow problem.
51
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)
}
52
Note : In Java, all method invocations are call-by-value.
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.
53
def delayed(t: => Int) = println("delayed method")
def notDelayed(t: Int) = println("Indelayed method")
def infinite() : Int = {
print("X")
infinite()
}
delayed(infinite()) // delayed method
notDelayed(infinite()) //XXXXXXXXXXXXXXXXXX…
def what(any:Any) = any match {
case i:Int => "It's an Int"
case s:String => "It's a String"
case _ => "I don't know what it is"
}
what(123) //"It's an Int"
what("hello") //"It's a String"
what(false) //"I don't know what it is"
54
val books = List("Beginning Scala", "Beginning Groovy",
"Beginning Java", "Scala in 24 hours")
for (book<-books) println(book)
var scalabooks =
for{ book <-books if book.contains("Scala") } yield book
> scalabooks: List[String] = List(Beginning Scala, Scala in 24 hours)
for(book<-books if book.contains("Scala") ) println(book)
books.foreach(println(_))
55
(1 to 20).filterNot(elem => elem % 2 == 0)
.filter(_ % 3 == 0)
.map(elem => elem * elem)
.foldLeft(1)(_ * _) //164025
import scala.io.Source // count characters occurrences
val lines = Source.fromFile(“path").getLines()
lines.flatMap(_.toCharArray)
.foldLeft(Map[Char, Int]() withDefaultValue 0)
((acc, c) => acc updated (c, acc(c)+1))
56
57
58
• Functional Programming in Scala
Specialization on Coursera.
• Explore Scala Ecosystem, especially Akka and
Play.
• Think Functional; don’t look over books and
tutorial with such a name like “Scala for X
developers”
• Learn Functional Reactive Programming in
Scala.
• Explore other advanced futures of Scala like
Macros, DSL & Parser Combinator, Monad
and Monoid, …
59
60

Mais conteúdo relacionado

Mais procurados

If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
Mario Fusco
 
JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and Functions
Jussi Pohjolainen
 

Mais procurados (20)

Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) Language
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Oops in Java
Oops in JavaOops in Java
Oops in Java
 
Core java
Core javaCore java
Core java
 
Java presentation
Java presentation Java presentation
Java presentation
 
Scala: functional programming for the imperative mind
Scala: functional programming for the imperative mindScala: functional programming for the imperative mind
Scala: functional programming for the imperative mind
 
Introduction to Rust language programming
Introduction to Rust language programmingIntroduction to Rust language programming
Introduction to Rust language programming
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
 
Java Quiz Questions
Java Quiz QuestionsJava Quiz Questions
Java Quiz Questions
 
Groovy presentation
Groovy presentationGroovy presentation
Groovy presentation
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
 
Core java Essentials
Core java EssentialsCore java Essentials
Core java Essentials
 
Boost your productivity with Scala tooling!
Boost your productivity  with Scala tooling!Boost your productivity  with Scala tooling!
Boost your productivity with Scala tooling!
 
Introduce yourself to java 17
Introduce yourself to java 17Introduce yourself to java 17
Introduce yourself to java 17
 
GraalVM
GraalVMGraalVM
GraalVM
 
What Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
What Is Java | Java Tutorial | Java Programming | Learn Java | EdurekaWhat Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
What Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
 
JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and Functions
 

Semelhante a Quick introduction to scala

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
 
AestasIT - Internal DSLs in Scala
AestasIT - Internal DSLs in ScalaAestasIT - Internal DSLs in Scala
AestasIT - Internal DSLs in Scala
Dmitry Buzdin
 

Semelhante a Quick introduction to scala (20)

Scala final ppt vinay
Scala final ppt vinayScala final ppt vinay
Scala final ppt vinay
 
Scala and jvm_languages_praveen_technologist
Scala and jvm_languages_praveen_technologistScala and jvm_languages_praveen_technologist
Scala and jvm_languages_praveen_technologist
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
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
 
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
 
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
 
Introduction to Scala language
Introduction to Scala languageIntroduction to Scala language
Introduction to Scala language
 
Scala presentationjune112011
Scala presentationjune112011Scala presentationjune112011
Scala presentationjune112011
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
 
Scala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud Foundry
 
Sviluppare applicazioni nell'era dei "Big Data" con Scala e Spark - Mario Car...
Sviluppare applicazioni nell'era dei "Big Data" con Scala e Spark - Mario Car...Sviluppare applicazioni nell'era dei "Big Data" con Scala e Spark - Mario Car...
Sviluppare applicazioni nell'era dei "Big Data" con Scala e Spark - Mario Car...
 
Cassandra Summit 2014: Apache Spark - The SDK for All Big Data Platforms
Cassandra Summit 2014: Apache Spark - The SDK for All Big Data PlatformsCassandra Summit 2014: Apache Spark - The SDK for All Big Data Platforms
Cassandra Summit 2014: Apache Spark - The SDK for All Big Data Platforms
 
Beginning scala 02 15
Beginning scala 02 15Beginning scala 02 15
Beginning scala 02 15
 
A Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to ScalaA Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to Scala
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Martin Odersky: What's next for Scala
Martin Odersky: What's next for ScalaMartin Odersky: What's next for Scala
Martin Odersky: What's next for Scala
 
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
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
AestasIT - Internal DSLs in Scala
AestasIT - Internal DSLs in ScalaAestasIT - Internal DSLs in Scala
AestasIT - Internal DSLs in Scala
 

Mais de Mohammad Hossein Rimaz

Mais de Mohammad Hossein Rimaz (6)

004 - JavaFX Tutorial - Event Handling
004 - JavaFX Tutorial - Event Handling004 - JavaFX Tutorial - Event Handling
004 - JavaFX Tutorial - Event Handling
 
003 - JavaFX Tutorial - Layouts
003 - JavaFX Tutorial - Layouts003 - JavaFX Tutorial - Layouts
003 - JavaFX Tutorial - Layouts
 
002- JavaFX Tutorial - Getting Started
002- JavaFX Tutorial - Getting Started002- JavaFX Tutorial - Getting Started
002- JavaFX Tutorial - Getting Started
 
Java 9, JShell, and Modularity
Java 9, JShell, and ModularityJava 9, JShell, and Modularity
Java 9, JShell, and Modularity
 
Continuous integration with Jenkins
Continuous integration with JenkinsContinuous integration with Jenkins
Continuous integration with Jenkins
 
JavaFX in Action Part I
JavaFX in Action Part IJavaFX in Action Part I
JavaFX in Action Part I
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 

Quick introduction to scala

  • 1. @ 1
  • 2. • Introduction • Basics of Scala Programming Language • Object-Oriented Programming with Scala • Functional Programming with Scala • The Road Ahead • Q&A 2
  • 3. 3
  • 4. Is so named because it was designed to grow with the demands of its users. 4 Scala is an acronym for Scalable Language
  • 5. 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. 5
  • 6. If we were forced to name just one aspect of Scala that helps scalability, we’d pick it combination of object-oriented and functional programming. 6 Agile, with lightweight syntax No boilerplate code Object-Oriented Functional Safe and Performant, with strong static typing
  • 7. • 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. 7
  • 8. • 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. 8
  • 9. James Gosling, the creator of the Java programming language 9 If I were to pick a language to use today other than Java, it would be Scala.
  • 10. 10
  • 11. • 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 11
  • 12. • 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. 12
  • 13. • Apache Kafka is written in Scala and Java. It provides a unified, high-throughput, low-latency platform for handling real-time data feeds. 13
  • 14. • Apache Samza is a distributed stream processing framework written in Java and Scala. It uses Apache Kafka for messaging, and Apache Hadoop YARN to provide fault tolerance, processor isolation, security, and resource management. 14
  • 15. • Apache Flink is a distributed streaming dataflow engine written in Java and Scala. 15
  • 16. • Play is a stateless, asynchronous, and non-blocking framework that uses an underlying fork-join thread pool to do work stealing for network operations, and can leverage Akka for user level operations. • Play Framework makes it easy to build web applications with Java & Scala. 16
  • 17. • Lift claim that it is the most powerful, most secure web framework available today. • It’s Secure, Scalable, Modular, Designer friendly, and Developer centric. 17
  • 18. • Spray is an open-source toolkit for building REST/HTTP-based integration layers on top of Scala and Akka. • Being asynchronous, actor-based, fast, lightweight, modular and testable it's a great way to connect your Scala applications to the world. 18
  • 19. • Scalatra is a simple, accessible and free web micro-framework. • It combines the power of the JVM with the beauty and brevity of Scala, helping you quickly build high-performance web sites and APIs. 19
  • 20. • Akka is open source middleware for building highly concurrent, distributed and fault-tolerant systems on the JVM. • Akka is built with Scala, but offers both Scala and Java APIs to developers. • At the heart of Akka is the concept of Actors, which provide an ideal model for thinking about highly concurrent and scalable systems. 20
  • 21. • Scala NLP library including Breeze, Epic, Puck. • Wisp is a web-based plotting library. • ADAM is a genomics processing engine and specialized file format built using Apache Avro, Apache Spark and Parquet. • Scala-Chart is another library for creating and working with carts. • Scalalab is an easy and efficient MATLAB-like scientific computing library in Scala 21
  • 23. 23
  • 24. 24 • 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 val name = "KNTU“ > name: String = KNTU val id = 12L > id: Long = 12 val pi:Float = 3.14F > pi: Float = 3.14
  • 25. 25
  • 26. • Byte • Short • Int • Long • Float • Double • Char • Boolean • Unit 26 var a:Int=2 > a: Int = 2 var a:Double=2.2 > a: Double = 2.2 var a:Float=2.2F > a: Float = 2.2 var a:Byte=4 > a: Byte = 4 var a:Boolean=false > a: Boolean = false println(a) > false res0: Unit = ()
  • 27. // variable var name = "foo" name = "bar" // value val age = 18 age = 20 27
  • 28. • An expression-oriented programming language is a programming language where every (or nearly every) construction is an expression and thus yields a value. • All functional programming languages are expression-oriented. • As we seen, even “println” has return value of type Unit. 28
  • 29. val name = "KNTU" > name: String = KNTU if(name.length == 1.*(4)) "*" else "#" > res0: String = * val name = "Rimaz" > name: String = Rimaz if(name.length() == 1 * 4){ "*" } else{ "#" } > res0: String = # 29
  • 30. var count = 0 while(count < 10) count+=1 var count = 0 do count+=2 while(count<10) Note: Avoid imperative style of programming like while loops and mutation, Think Functional. 30
  • 31. 31
  • 32. val range = 1 to 10 > range: scala.collection.immutable.Range.Inclusive = Range 1 to 10 println(range.last) // 10 val range2 = 1 until 10 > range2: scala.collection.immutable.Range = Range 1 until 10 println(range2.last) // 9 val range3 = 1 until 10 by 3 > range3: scala.collection.immutable.Range = Range 1 until 10 by 3 println(range3.last) // 7 32
  • 33. 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)) print(tuples._1) > 10 print(tuples._2) > ten print(tuples._6._2) > NINE 33
  • 34. var lst=List("b","c","d") > lst: List[String] = List(b, c, d) print(lst.head) > b print(lst.tail) > List(c, d) var lst2="a"::lst > lst2: List[String] = List(a, b, c, d) var l=1::2::3::4::Nil > l: List[Int] = List(1, 2, 3, 4) var l2=l::List(5,6) > l2: List[Any] = List(List(1, 2, 3, 4), 5, 6) var l3=l:::List(5,6) > l3: List[Int] = List(1, 2, 3, 4, 5, 6) 34
  • 35. var array=new Array[String](3) > array: Array[String] = Array(null, null, null) var at=Array(4,4.7,"Gasai Yuno") > at: Array[Any] = Array(4, 4.7, Gasai Yuno) val mat = Array.ofDim[Int](3,4) mat(1)(2) = 3 35
  • 36. val books = List("Beginning Scala", "Beginning Groovy", "Beginning Java", "Scala in 24 hours") for (book<-books) println(book) var scalabooks = for{ book <-books if book.contains("Scala") } yield book > scalabooks: List[String] = List(Beginning Scala, Scala in 24 hours) for(book<-books if book.contains("Scala") ) println(book) 36
  • 37. 37
  • 38. import scala.math.{sqrt,pow} //abs is not visible class Person(val name: String, var age: Int) {} var p = new Person("Peter", 21) p.age += 1 class Point(private var x: Double, val y: Double) { def distanceTo(o:Point) = sqrt(pow(x-o.x,2) + pow(y-o.y,2)) } var p1 = new Point(3,4) //p1.y += 1, y is value not varibale var p2 = new Point(3,6) println(p1.distanceTo(p2)) //2 38
  • 39. • 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 39
  • 40. 40 // 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 Person.defaultName()
  • 41. 41 Implicitly override toString, equals, hashCode • take object’s structure into account • Useful in pattern matching case class Person(private val name: String, private val age: Int) {} val p1 = new Person("Hossein",21) > p1: Person = Person(Hossein,21) val p2 = Person("Hossein",21) p1 == p2 //== is equivalent to equals
  • 42. 42 Traits are used to share interfaces and fields between classes. They are similar to Java 8’s interfaces. trait Pet { val name: String def greet(): String = { return s"Hi, I'm ${name}" } } case class Dog(name:String) extends Pet val dog = Dog("Hachi") dog.greet() > res0: String = Hi, I’m Hachi
  • 43. 43 Mixins are a language concept that allows a programmer to inject some code into a class. Typically, the mixin will export the desired functionality to a child class, without creating a rigid, single "is a" relationship. It provides a mechanism for multiple inheritance by allowing multiple classes to use the common functionality, but without the complex semantics of multiple inheritance. Mixins encourage code reuse and can be used to avoid the inheritance ambiguity that multiple inheritance can cause (the "diamond problem")
  • 44. 44 trait Language { val name:String override def toString = name } trait JVM { override def toString = super.toString+" runs on JVM" } trait Static { override def toString = super.toString+" is Static" } class Scala extends Language with JVM with Static { val name = "Scala" } println(new Scala) // Scala runs on JVM is Static
  • 45. 45
  • 46. • First-class functions - Functions as variables, method parameters, and return value • Pure functions - No side effect • Recursion • Immutable variables • Non-Strict evaluation - Delay evaluation until the last moment • Statements - Expression-Oriented • Pattern matching 46
  • 47. def fibo(n:Int) : Int = if(n<2) n else fibo(n-1) + fibo(n-2) > fibo: fibo[](val n: Int) => Int for( i <- 0 to 10) yield fibo(i) > res0: res0: scala.collection.immutable.IndexedSeq[Int] = Vector(0, 1, 1, 2, 3, 5, 8, 13) 47
  • 48. def func(x:Int,y:Int, z:(Int,Int)=>Int): Int = z.apply(x,y) func(2,3,(x,y)=> x*y) val adder = (x:Int,y:Int)=> x+y func(2,3,adder) func(2,3,(x,y)=> (x*x-y*y).abs) 48
  • 49. var offset = 1 val plusOffset = (x:Int) => x + offset plusOffset(5) // 6 foo = 5 plusOffset(5) // 10 A Closure is a function, whose return value depends on the value of one or more variables declared outside this function. 49
  • 50. 50 Tail Recursive function is a function calls itself as its final operation. A Tail Recursive Function can automatically optimized by compiler to avoid Stack Overflow problem.
  • 51. 51 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) }
  • 52. 52 Note : In Java, all method invocations are call-by-value. 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.
  • 53. 53 def delayed(t: => Int) = println("delayed method") def notDelayed(t: Int) = println("Indelayed method") def infinite() : Int = { print("X") infinite() } delayed(infinite()) // delayed method notDelayed(infinite()) //XXXXXXXXXXXXXXXXXX…
  • 54. def what(any:Any) = any match { case i:Int => "It's an Int" case s:String => "It's a String" case _ => "I don't know what it is" } what(123) //"It's an Int" what("hello") //"It's a String" what(false) //"I don't know what it is" 54
  • 55. val books = List("Beginning Scala", "Beginning Groovy", "Beginning Java", "Scala in 24 hours") for (book<-books) println(book) var scalabooks = for{ book <-books if book.contains("Scala") } yield book > scalabooks: List[String] = List(Beginning Scala, Scala in 24 hours) for(book<-books if book.contains("Scala") ) println(book) books.foreach(println(_)) 55
  • 56. (1 to 20).filterNot(elem => elem % 2 == 0) .filter(_ % 3 == 0) .map(elem => elem * elem) .foldLeft(1)(_ * _) //164025 import scala.io.Source // count characters occurrences val lines = Source.fromFile(“path").getLines() lines.flatMap(_.toCharArray) .foldLeft(Map[Char, Int]() withDefaultValue 0) ((acc, c) => acc updated (c, acc(c)+1)) 56
  • 57. 57
  • 58. 58
  • 59. • Functional Programming in Scala Specialization on Coursera. • Explore Scala Ecosystem, especially Akka and Play. • Think Functional; don’t look over books and tutorial with such a name like “Scala for X developers” • Learn Functional Reactive Programming in Scala. • Explore other advanced futures of Scala like Macros, DSL & Parser Combinator, Monad and Monoid, … 59
  • 60. 60