SlideShare a Scribd company logo
1 of 60
Download to read 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

More Related Content

What's hot

Quarkus - a next-generation Kubernetes Native Java framework
Quarkus - a next-generation Kubernetes Native Java frameworkQuarkus - a next-generation Kubernetes Native Java framework
Quarkus - a next-generation Kubernetes Native Java framework
SVDevOps
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
pramode_ce
 

What's hot (20)

Quarkus - a next-generation Kubernetes Native Java framework
Quarkus - a next-generation Kubernetes Native Java frameworkQuarkus - a next-generation Kubernetes Native Java framework
Quarkus - a next-generation Kubernetes Native Java framework
 
Apache Spark Fundamentals
Apache Spark FundamentalsApache Spark Fundamentals
Apache Spark Fundamentals
 
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 Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 
Introduction to GraalVM
Introduction to GraalVMIntroduction to GraalVM
Introduction to GraalVM
 
Oscon keynote: Working hard to keep it simple
Oscon keynote: Working hard to keep it simpleOscon keynote: Working hard to keep it simple
Oscon keynote: Working hard to keep it simple
 
What's new in Java 11
What's new in Java 11What's new in Java 11
What's new in Java 11
 
Scala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationScala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentation
 
Apache Spark Architecture
Apache Spark ArchitectureApache Spark Architecture
Apache Spark Architecture
 
OOP and FP
OOP and FPOOP and FP
OOP and FP
 
Quarkus k8s
Quarkus   k8sQuarkus   k8s
Quarkus k8s
 
Devoxx France 2023 - 1,2,3 Quarkus.pdf
Devoxx France 2023 - 1,2,3 Quarkus.pdfDevoxx France 2023 - 1,2,3 Quarkus.pdf
Devoxx France 2023 - 1,2,3 Quarkus.pdf
 
Introduction to JAVA
Introduction to JAVAIntroduction to JAVA
Introduction to JAVA
 
Discover Quarkus and GraalVM
Discover Quarkus and GraalVMDiscover Quarkus and GraalVM
Discover Quarkus and GraalVM
 
Introduction to Apache Spark
Introduction to Apache SparkIntroduction to Apache Spark
Introduction to Apache Spark
 
Java 101 intro to programming with java
Java 101  intro to programming with javaJava 101  intro to programming with java
Java 101 intro to programming with java
 
Empowering Your Java Applications with Quarkus. A New Era of Fast, Efficient,...
Empowering Your Java Applications with Quarkus. A New Era of Fast, Efficient,...Empowering Your Java Applications with Quarkus. A New Era of Fast, Efficient,...
Empowering Your Java Applications with Quarkus. A New Era of Fast, Efficient,...
 
Introduction to Apache Kafka
Introduction to Apache KafkaIntroduction to Apache Kafka
Introduction to Apache Kafka
 
JAVA PROGRAMMING
JAVA PROGRAMMING JAVA PROGRAMMING
JAVA PROGRAMMING
 
Kafka Tutorial - Introduction to Apache Kafka (Part 1)
Kafka Tutorial - Introduction to Apache Kafka (Part 1)Kafka Tutorial - Introduction to Apache Kafka (Part 1)
Kafka Tutorial - Introduction to Apache Kafka (Part 1)
 

Similar to 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
 

Similar to 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
 
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
 
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...
 

More from Mohammad Hossein Rimaz

More from 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
 

Recently uploaded

+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@
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Recently uploaded (20)

[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
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...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
+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...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
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
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
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
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 

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