SlideShare a Scribd company logo
1 of 70
Download to read offline
IntroductiontoProgrammingin
Scala
Hungai Amuhinda
@hungai
hungaikev
hungaikev.in
hungaikevin@gmail.com
❖ Introduction
❖ Scala
OOP
FP
Concepts
❖
❖
❖ Collections
Agenda
What is Scala:
Scalaisthebestwaytowritescalable,resilientandmaintainable
softwareontheJVM(primarily).Itstypesystemhelpsavoidbugs
withoutgettinginyourway.It'sOOformodularity&extensibility;FPfor
compositionthatyoucanreasonabout.
Scala Concepts
• Scala is an object oriented language in pure form:
every value is an object and every operator is a
method.
• “ + ”, “ - ”, “ * ”, “ / ” are all methods
Scala Concepts
• Everythingisanexpression
• Expressionisaninstructiontoexecutesomethingthatwillreturna
value.
• Anexpressionevaluatestoaresultorresultsinavalue
• Expressions, Types and Values are the fundamental building blocks
for Scala Programs. Understanding these concepts is necessary to
build a mental model of how Scala programs work.
Scala Concepts
In the Scala console or worksheet enter "Hello world!" and press return (in the
console) or save the worksheet. You should see an interaction similar to this:
In your console type “Hello world!”.toUpperCase
Scala Concepts
Compile time and Runtime
• Two distinct stages that a Scala program goes through: first it is
compiled, and if it compiles successfully it can then be run or
evaluated.
• It is important to understand that compile time and
runtime really are distinct, as it is this distinction that allows
us to properly understand the difference between types
and values.
• Compilation is a process of checking that a program makes
sense.
WhatareTypes
• Types are restrictions on our programs that limit how we can
manipulate objects.
• We have already seen two types, String and Int, and seen that
we can perform different operations depending on the type.
• The most important point about types is that expressions
have types but values do not.
Scala’sBasicDataTypes
● Double
● String
● Float
● Char
● Boolean
● Byte
● Short
● Int
● Long
Scala Class Hierarchy
scala.Any
scala.AnyVal scala.AnyRef
scala.Int scala.List scala.String
scala.Byte scala.Seq
scala.Boolean
scala.Map
scala.Char
Take Home Points.
• WemustbuildamentalmodelofScalaprogramsifwearetouseScala.
Threefundamentalcomponentsofthismodelare expressions,types,and
values.
• Expressionsarethepartsofaprogramthatevaluatetoavalue.Theyare
themajorpartofaScalaprogram.
• Expressionshavetypes,whichexpresssomerestrictionsonprograms.
Duringcompiletimethetypesofourprogramsarechecked.Iftheyare
inconsistentthencompilationfailsandwecannotevaluate,orrun,our
program.
● Static
● Inferred(TypeInference)
● Structural
● Strong
Scala
Concepts(Advanced
TypeSystem)
(Worksheet)
Demo04
Program with Scala
Work with worksheets
● IntelliJ
● Scala IDE or Eclipse
with Scala Plugin
● Ensime
Program with Scala (Main)
Demo01
object Demo1 {
def main (args: Array[String]): Unit = {
println(“Hello Everyone”)
println(“Welcome to today’s workshop”)
}
}
Program with Scala (App)
Demo02
object Demo2 extends App {
val todaysEvent = “Nairobi JVM”
lazy val fun = (0 to 4).map(x => “fun”).mkString(“ ”)
println(“Hello world”)
println(“Welcome to ” + todaysEvent + “! n”)
}
Scala Concepts
❖ var, val
❖ If expressions
❖ def
❖ Block expressions
❖ While - Loops
❖ For - Loops
❖ Nested Function
❖ Recursion vs Tail recursion
❖ Pattern Matching
Scala Concepts
Demo05
❖ val - value
A value is an expression
that cannot be changed
any further
(Immutable)
It's similar to final in
Java
❖ var - variable
Something that is able or
likely to change or be
changed (Mutable)
Expression with Semicolon?
= “scala”
one
Demo06
val x = 5566
val y = 87
val java = “Java” ; val scala
If you have multiple expressions in
line, you will need semicolons(;).
Otherwise you don't need it.
The syntax for a conditional expression is:
If(condition)
trueExpression
else
falseExpression
Where:
1. condition is an expression with Boolean type
2. trueExpression is the expression evaluated if condition evaluates
to true
3. falseExpression is the expression evaluated if condition evaluates
to false
If Expressions
Demo02
If Expressions
Demo07
❖ If has return value (expression)
❖ Scala has no ternary operator (? : )
val value = 0
val negative = If (value < 0 ) true else false
Everything is an expression
“def” starts a function definition
Result type of function
Function name
braces
Demo08
Parameters Equals sign
def max (x: Int, y: Int): Int = {
If (x > y) x else y
} Function body in Curly
def
def
Demo09
def max (x: Int, y: Int): Int = {
If (x > y)
return x
else
return y
}
def
y
Demo010
def max (x: Int, y: Int) = {
If (x > y)
x
else
}
No Result type
def
Demo011
def max (x: Int, y: Int) =
If (x > y)
x
else No Curly brackets
y
Summary of def
❖ You don't need a return statement
- Last expression of a block will be the return value
❖ You don't need return type in method or function definition.
- Scalac will infer your return type in most cases. Its a good habit
to have a return type, especially if your API has a public
interface
❖ You don't need curly brackets
- If you have multiple lines of code, using curly brackets ({ }) is a
good habit
Block expressions (Curly brackets)
return value, then it will be assign result to
Demo012
val n = 5
val factorial = {
var result = 1
for (i <- 1 to n )
result = result * i
result
} Last expression (result) in block will be the
“factorial”
Demo013
WhileLoop
var n = 10
var sum = 0
while (n > 0) {
sum = sum + 1
n = n - 1
}
Demo014
For-Loop
var sum = 0
for (i <- 1 to 10) {
sum += 1
}
println(sum)
Nested Function
Demo015
def min (x: Int, y: Int): Int = {
def max (x: Int, y: Int) = {
if (x > y)
x
else
y
}
if (x >= max(x,y)) y else x
}
Recursion vsTail Recursion
Recursion vs Tail - recursion
Demo016
def factorial(n : Int): BigInt = {
If (n == 0) 1
else
n * factorial(n - 1)
}
factorial (15)
factorial (150)
factorial(15000) // java.lang.StackOverflowError
Recursion vs Tail - recursion
factorial(15000)
Demo017
def factorial(n : Int): BigInt = {
def helpFunction(acc : BigInt, n: Int) : BigInt
= {
If (n == 0)
acc
else
helpFunction(acc * n , n -1 )
}
helpFunction(1,n) “Tail - Recursion”
}
Recursion vs Tail - recursion
import scala.annotation.tailrec “Add annotation is a good habit. Compiler
can check whether or not it can bedef factorial(n : Int): BigInt = {
@tailrec optimised. ”
def helpFunction(acc : Int, n: Int) : BigInt = {
If (n == 0)
acc
else
helpFunction(acc * n , n -1 )
}
helpFunction(1,n)
“You have to add a return type, when the
function is recursive”
}
factorial(15000)
Demo018
Pattern Matching
- It can match anything
Pattern matching is a feature that is very common in functional
languages
❖ It matches a value against an expression
❖ Each pattern points to an expression
It's similar to “switch case” but its more general. There are some
differences:
- No fall through
- Each condition needs to return a value(Everything in scala is an
expression)
Pattern Matching
Demo019
def matchString(x : String): String = {
x match {
case “Dog” => x
case “Cat” => “Not a cat person”
case _ => “Neither Dog or Cat”
}
matchString(“Dog”)
matchString(“Human”)
OOP
Scala (Object Oriented)
v Classes
v Extends , with, override
v Abstract classes
v Objects,
v Companion objects
v Traits
v Case classes
Classes
Demo020
Primary Constructor valin constructor willgiveyoua getter
class Employee(id : Int, val name: String, address: String, var salary: Long
)
var in constructor will give you a getter and setter
val employee = new Employee(1,”Hungai”,”Kakamega”,40L)
Extends, with, override.
Single inheritance enables a derived class to inherit
properties and behaviour from a single parent class
❖ Scala is single inheritance like Java.
❖ Scala - extends = Java - extends
❖ Scala - with = Java - implements
❖ Scala - override = Java - @Override
Abstract classes.
Abstract classes are just like normal classes but can have abstract
methods and abstract fields
In scala, you don't need the keyword abstract for methods and fields
in an abstract class
Abstract classes.
def speaks : Unit
Demo021
abstract class Animal (val name: String) {
val footNumber: Int
val fly : Boolean Subclasses should be in the same file.
}
class Dog(name: String) extends Animal (name) {
override val footNumber : Int = 4
override val fly = false
override def speak : Unit = println(“Spark”)
}
class Bird(name : String) extends Animal(name) {
override val footNumber : Int = 2
override val fly = true
override def speaks: Unit = println(“chatter”)
}
Objects.
• A singleton object is declared using the object keyword.
• When a singleton object shares the same name with a class it's referred
to as a Companion object.
• A companion object and its classes can access each others private
methods or fields
Singleton Object.
Demo022
object MathUtil {
def doubleHalfUp(precision: Int, origin: Double): Double {
val tmp = Math.pow(10,precision)
Math.round(origin * tmp)/ tmp
}
}
Case Classes.
Case classes are just regular classes that are :
➔ Immutable by default
➔ Decomposable through pattern matching
➔ Compared by structural equality instead of by reference.
When you declare a case class the scala compiler does the following for you:
➔ Creates a class and its companion object
Implements the ‘apply’ method that you can use a factory. This lets you
create instances of the class without the ‘new’ keyword
Case classes.
Demo023
abstract class Notification
case class Email(sourceEmail: String, title: String, body: String) extends Notification.
case class SMS (sourceNumber: String, message: String) extends Notification.
case class VoiceRecording(contactName: String, link: String) extends Notification.
val emailNotification = Email(“h@hungaikev.in”,”Scavannah”,”Todays lesson”)
println(emailNotification)
FP
Demo012
Alonzo Church 1930
TheLambdaCalculus.
❖ Theoretical foundation
❖ Pure functions - no state
❖ Not a programming language
Lambda Ca lculus.
Variable Expressions
ƛx . x + 1
Function Application
Lambda Ca lculus.
Demo024
ƛx . x + 1
// Scala Translation
{ x : Int => x + 1 }
Scala (Functional)
❖ Functional Concepts
❖ First class functions
❖ Anonymous functions
❖ Higher order functions
Functional Concepts.
Demo012
Immutability (Referential Transparency - Expressions always evaluates to
the same result in any context)
- No side effects (Modifies state, Not predictable)
❖ Functions as values
- Functions as objects
Higher order functions - Input: Takes one or more functions as parameters,
Output: Returns a function as result
Demo012
Anonymous functions (Lambdas).
Anonymous functions.
Demo025
((x : Int ) => x * x)
(0 until 10).map ((value: Int) => value * value)
(0 until 10).map (value => value * value )
(0 until 10).map (value => value + 1)
(0 until 10).map (_ + 1)
High-order Functions.
Demo026
def calculateTax(rate: BigDecimal => BigDecimal, salary: BigDecimal) : BigDecimal = {
rate(salary)
}
val kenyaTax = (salary: BigDecimal) => {
if (salary > 413201) salary * 0.396 else salary * 0.3
}
val tzTax: BigDecimal => BigDecimal = _ * 0.25
calculateTax(kenyaTax,413201)
calculateTax(tzTax,100)
High-order Functions.
Demo027
def calculateTax(rate: BigDecimal => BigDecimal, salary: BigDecimal) : BigDecimal = {
rate(salary)
}
def kenyaTax (salary: BigDecimal) = {
calculateTax(x =>
if (salary > 413201) salary * 0.396 else salary * 0.3, salary )
}
def tzTax(salary: BigDecimal ) =
calculateTax( _ * 0.25, salary)
kenyaTax(413202)
tzTax(100)
High-order Functions.
Demo028
def calculateTax(rate: BigDecimal => BigDecimal) : (BigDecimal ) => BigDecimal = {
rate
}
def kenyaTax = calculateTax(x => if (x > 413201) x * 0.396 else x * 0.3 )
def tzTax = calculateTax( x => x * 0.25)
kenyaTax(413202)
tzTax(100)
calculateTax(kenyaTax)(413202)
calculateTax(tzTax)(100)
High-order Functions - Curry.
Demo029
def calculateTax(rate: BigDecimal => BigDecimal) (salary : BigDecimal ) : BigDecimal =
{
rate (salary)
}
def kenyaTax(salary : BigDecimal) = calculateTax(x => if (x > 413201) x * 0.396 else x *
0.3 )(salary)
def tzTax(salary : BigDecimal) = calculateTax( x => x * 0.25)(salary)
kenyaTax(413202)
tzTax(100)
Collections
Collections
❖
❖ Concept of Collections
❖ Hierarchy of Collections
- Immutable
- Mutable
❖ Immutable List
Collections.
❖ Scala supports mutable collections and immutable collections.
A mutable collection can be updated or extended in place. This means you
can change, add or remove elements as a side effect.
Immutable collections never change. You have still operations that stimulate
additions, removals, updates by creating a new collection and leave the old
unchanged.
Collections Hierarchy
Hierarchy ofImmutable Collections
Hierarchy of mutable Collections
val list1 = List(1,2,3)
Demo030
// Construct a List Pronounced “cons”
val list2 = 1 :: 2 :: 3 :: 4 :: 5 :: Nil
val list3 = List(“apples”, “oranges”,”bananas”)
val list4 = List(5,5,6,6) ::: List(8,7)
Immutable List
Demo031
val list = List(4,3,0,1,2)
➔ list.head ➔ list.sortWith(_ > _)
➔ list.tail ➔ list.map(x => x * 2)
➔ list.length ➔ list.map(_ * 2)
➔ list.max ➔ list.reduce((x,y) => x + y)
➔ list.min ➔ list.filter(_ % 2 == 0)
➔ list.sum ➔ list.groupBy(x => x % 2 == 0)
➔ list.contains(2)
➔ list.drop
➔ list.reverse
ImmutableList(API)
Summary of Scala.
❖ Keep it simple
❖ Don’t pack too much in one expression
❖ Find meaningful names
❖ Prefer functional
❖ Careful with mutable objects
Further Reading $ References.
❖ ScalaOfficial Docs
❖ Cousera-MartinOdesky
❖ CreativeScala
❖ ScalaSchool byTwitter
❖ Scala101byLightbend
Q&A

More Related Content

What's hot

scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 

What's hot (18)

camel-scala.pdf
camel-scala.pdfcamel-scala.pdf
camel-scala.pdf
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
 
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
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Functional Programming in Scala
Functional Programming in ScalaFunctional Programming in Scala
Functional Programming in Scala
 
Introducing Akka
Introducing AkkaIntroducing Akka
Introducing Akka
 
Scala
ScalaScala
Scala
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
Google06
Google06Google06
Google06
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
 
Ankara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with ScalaAnkara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with Scala
 
Quick introduction to scala
Quick introduction to scalaQuick introduction to scala
Quick introduction to scala
 
Scala basic
Scala basicScala basic
Scala basic
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
 
ScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin OderskyScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin Odersky
 

Similar to Introductiontoprogramminginscala

Knolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaKnolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in Scala
Ayush Mishra
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
Miles Sabin
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
Skills Matter
 

Similar to Introductiontoprogramminginscala (20)

Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf Taiwan
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Scala on Android
Scala on AndroidScala on Android
Scala on Android
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
 
Knolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaKnolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in Scala
 
Intro to Scala
 Intro to Scala Intro to Scala
Intro to Scala
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java Developers
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
Traits inscala
Traits inscalaTraits inscala
Traits inscala
 
Traits in scala
Traits in scalaTraits in scala
Traits in scala
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010
 

Recently uploaded

The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 

Recently uploaded (20)

Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 

Introductiontoprogramminginscala

  • 5. Scala Concepts • Scala is an object oriented language in pure form: every value is an object and every operator is a method. • “ + ”, “ - ”, “ * ”, “ / ” are all methods
  • 6. Scala Concepts • Everythingisanexpression • Expressionisaninstructiontoexecutesomethingthatwillreturna value. • Anexpressionevaluatestoaresultorresultsinavalue • Expressions, Types and Values are the fundamental building blocks for Scala Programs. Understanding these concepts is necessary to build a mental model of how Scala programs work.
  • 7. Scala Concepts In the Scala console or worksheet enter "Hello world!" and press return (in the console) or save the worksheet. You should see an interaction similar to this:
  • 8. In your console type “Hello world!”.toUpperCase Scala Concepts
  • 9. Compile time and Runtime • Two distinct stages that a Scala program goes through: first it is compiled, and if it compiles successfully it can then be run or evaluated. • It is important to understand that compile time and runtime really are distinct, as it is this distinction that allows us to properly understand the difference between types and values. • Compilation is a process of checking that a program makes sense.
  • 10. WhatareTypes • Types are restrictions on our programs that limit how we can manipulate objects. • We have already seen two types, String and Int, and seen that we can perform different operations depending on the type. • The most important point about types is that expressions have types but values do not.
  • 11. Scala’sBasicDataTypes ● Double ● String ● Float ● Char ● Boolean ● Byte ● Short ● Int ● Long
  • 12. Scala Class Hierarchy scala.Any scala.AnyVal scala.AnyRef scala.Int scala.List scala.String scala.Byte scala.Seq scala.Boolean scala.Map scala.Char
  • 13. Take Home Points. • WemustbuildamentalmodelofScalaprogramsifwearetouseScala. Threefundamentalcomponentsofthismodelare expressions,types,and values. • Expressionsarethepartsofaprogramthatevaluatetoavalue.Theyare themajorpartofaScalaprogram. • Expressionshavetypes,whichexpresssomerestrictionsonprograms. Duringcompiletimethetypesofourprogramsarechecked.Iftheyare inconsistentthencompilationfailsandwecannotevaluate,orrun,our program.
  • 14. ● Static ● Inferred(TypeInference) ● Structural ● Strong Scala Concepts(Advanced TypeSystem)
  • 15. (Worksheet) Demo04 Program with Scala Work with worksheets ● IntelliJ ● Scala IDE or Eclipse with Scala Plugin ● Ensime
  • 16. Program with Scala (Main) Demo01 object Demo1 { def main (args: Array[String]): Unit = { println(“Hello Everyone”) println(“Welcome to today’s workshop”) } }
  • 17. Program with Scala (App) Demo02 object Demo2 extends App { val todaysEvent = “Nairobi JVM” lazy val fun = (0 to 4).map(x => “fun”).mkString(“ ”) println(“Hello world”) println(“Welcome to ” + todaysEvent + “! n”) }
  • 18. Scala Concepts ❖ var, val ❖ If expressions ❖ def ❖ Block expressions ❖ While - Loops ❖ For - Loops ❖ Nested Function ❖ Recursion vs Tail recursion ❖ Pattern Matching
  • 19. Scala Concepts Demo05 ❖ val - value A value is an expression that cannot be changed any further (Immutable) It's similar to final in Java ❖ var - variable Something that is able or likely to change or be changed (Mutable)
  • 20. Expression with Semicolon? = “scala” one Demo06 val x = 5566 val y = 87 val java = “Java” ; val scala If you have multiple expressions in line, you will need semicolons(;). Otherwise you don't need it.
  • 21. The syntax for a conditional expression is: If(condition) trueExpression else falseExpression Where: 1. condition is an expression with Boolean type 2. trueExpression is the expression evaluated if condition evaluates to true 3. falseExpression is the expression evaluated if condition evaluates to false If Expressions Demo02
  • 22. If Expressions Demo07 ❖ If has return value (expression) ❖ Scala has no ternary operator (? : ) val value = 0 val negative = If (value < 0 ) true else false Everything is an expression
  • 23. “def” starts a function definition Result type of function Function name braces Demo08 Parameters Equals sign def max (x: Int, y: Int): Int = { If (x > y) x else y } Function body in Curly def
  • 24. def Demo09 def max (x: Int, y: Int): Int = { If (x > y) return x else return y }
  • 25. def y Demo010 def max (x: Int, y: Int) = { If (x > y) x else } No Result type
  • 26. def Demo011 def max (x: Int, y: Int) = If (x > y) x else No Curly brackets y
  • 27. Summary of def ❖ You don't need a return statement - Last expression of a block will be the return value ❖ You don't need return type in method or function definition. - Scalac will infer your return type in most cases. Its a good habit to have a return type, especially if your API has a public interface ❖ You don't need curly brackets - If you have multiple lines of code, using curly brackets ({ }) is a good habit
  • 28. Block expressions (Curly brackets) return value, then it will be assign result to Demo012 val n = 5 val factorial = { var result = 1 for (i <- 1 to n ) result = result * i result } Last expression (result) in block will be the “factorial”
  • 29. Demo013 WhileLoop var n = 10 var sum = 0 while (n > 0) { sum = sum + 1 n = n - 1 }
  • 30. Demo014 For-Loop var sum = 0 for (i <- 1 to 10) { sum += 1 } println(sum)
  • 31. Nested Function Demo015 def min (x: Int, y: Int): Int = { def max (x: Int, y: Int) = { if (x > y) x else y } if (x >= max(x,y)) y else x }
  • 33. Recursion vs Tail - recursion Demo016 def factorial(n : Int): BigInt = { If (n == 0) 1 else n * factorial(n - 1) } factorial (15) factorial (150) factorial(15000) // java.lang.StackOverflowError
  • 34. Recursion vs Tail - recursion factorial(15000) Demo017 def factorial(n : Int): BigInt = { def helpFunction(acc : BigInt, n: Int) : BigInt = { If (n == 0) acc else helpFunction(acc * n , n -1 ) } helpFunction(1,n) “Tail - Recursion” }
  • 35. Recursion vs Tail - recursion import scala.annotation.tailrec “Add annotation is a good habit. Compiler can check whether or not it can bedef factorial(n : Int): BigInt = { @tailrec optimised. ” def helpFunction(acc : Int, n: Int) : BigInt = { If (n == 0) acc else helpFunction(acc * n , n -1 ) } helpFunction(1,n) “You have to add a return type, when the function is recursive” } factorial(15000) Demo018
  • 36. Pattern Matching - It can match anything Pattern matching is a feature that is very common in functional languages ❖ It matches a value against an expression ❖ Each pattern points to an expression It's similar to “switch case” but its more general. There are some differences: - No fall through - Each condition needs to return a value(Everything in scala is an expression)
  • 37. Pattern Matching Demo019 def matchString(x : String): String = { x match { case “Dog” => x case “Cat” => “Not a cat person” case _ => “Neither Dog or Cat” } matchString(“Dog”) matchString(“Human”)
  • 38. OOP
  • 39. Scala (Object Oriented) v Classes v Extends , with, override v Abstract classes v Objects, v Companion objects v Traits v Case classes
  • 40. Classes Demo020 Primary Constructor valin constructor willgiveyoua getter class Employee(id : Int, val name: String, address: String, var salary: Long ) var in constructor will give you a getter and setter val employee = new Employee(1,”Hungai”,”Kakamega”,40L)
  • 41. Extends, with, override. Single inheritance enables a derived class to inherit properties and behaviour from a single parent class ❖ Scala is single inheritance like Java. ❖ Scala - extends = Java - extends ❖ Scala - with = Java - implements ❖ Scala - override = Java - @Override
  • 42. Abstract classes. Abstract classes are just like normal classes but can have abstract methods and abstract fields In scala, you don't need the keyword abstract for methods and fields in an abstract class
  • 43. Abstract classes. def speaks : Unit Demo021 abstract class Animal (val name: String) { val footNumber: Int val fly : Boolean Subclasses should be in the same file. } class Dog(name: String) extends Animal (name) { override val footNumber : Int = 4 override val fly = false override def speak : Unit = println(“Spark”) } class Bird(name : String) extends Animal(name) { override val footNumber : Int = 2 override val fly = true override def speaks: Unit = println(“chatter”) }
  • 44. Objects. • A singleton object is declared using the object keyword. • When a singleton object shares the same name with a class it's referred to as a Companion object. • A companion object and its classes can access each others private methods or fields
  • 45. Singleton Object. Demo022 object MathUtil { def doubleHalfUp(precision: Int, origin: Double): Double { val tmp = Math.pow(10,precision) Math.round(origin * tmp)/ tmp } }
  • 46. Case Classes. Case classes are just regular classes that are : ➔ Immutable by default ➔ Decomposable through pattern matching ➔ Compared by structural equality instead of by reference. When you declare a case class the scala compiler does the following for you: ➔ Creates a class and its companion object Implements the ‘apply’ method that you can use a factory. This lets you create instances of the class without the ‘new’ keyword
  • 47. Case classes. Demo023 abstract class Notification case class Email(sourceEmail: String, title: String, body: String) extends Notification. case class SMS (sourceNumber: String, message: String) extends Notification. case class VoiceRecording(contactName: String, link: String) extends Notification. val emailNotification = Email(“h@hungaikev.in”,”Scavannah”,”Todays lesson”) println(emailNotification)
  • 48. FP
  • 49. Demo012 Alonzo Church 1930 TheLambdaCalculus. ❖ Theoretical foundation ❖ Pure functions - no state ❖ Not a programming language
  • 50. Lambda Ca lculus. Variable Expressions ƛx . x + 1 Function Application
  • 51. Lambda Ca lculus. Demo024 ƛx . x + 1 // Scala Translation { x : Int => x + 1 }
  • 52. Scala (Functional) ❖ Functional Concepts ❖ First class functions ❖ Anonymous functions ❖ Higher order functions
  • 53. Functional Concepts. Demo012 Immutability (Referential Transparency - Expressions always evaluates to the same result in any context) - No side effects (Modifies state, Not predictable) ❖ Functions as values - Functions as objects Higher order functions - Input: Takes one or more functions as parameters, Output: Returns a function as result
  • 55. Anonymous functions. Demo025 ((x : Int ) => x * x) (0 until 10).map ((value: Int) => value * value) (0 until 10).map (value => value * value ) (0 until 10).map (value => value + 1) (0 until 10).map (_ + 1)
  • 56. High-order Functions. Demo026 def calculateTax(rate: BigDecimal => BigDecimal, salary: BigDecimal) : BigDecimal = { rate(salary) } val kenyaTax = (salary: BigDecimal) => { if (salary > 413201) salary * 0.396 else salary * 0.3 } val tzTax: BigDecimal => BigDecimal = _ * 0.25 calculateTax(kenyaTax,413201) calculateTax(tzTax,100)
  • 57. High-order Functions. Demo027 def calculateTax(rate: BigDecimal => BigDecimal, salary: BigDecimal) : BigDecimal = { rate(salary) } def kenyaTax (salary: BigDecimal) = { calculateTax(x => if (salary > 413201) salary * 0.396 else salary * 0.3, salary ) } def tzTax(salary: BigDecimal ) = calculateTax( _ * 0.25, salary) kenyaTax(413202) tzTax(100)
  • 58. High-order Functions. Demo028 def calculateTax(rate: BigDecimal => BigDecimal) : (BigDecimal ) => BigDecimal = { rate } def kenyaTax = calculateTax(x => if (x > 413201) x * 0.396 else x * 0.3 ) def tzTax = calculateTax( x => x * 0.25) kenyaTax(413202) tzTax(100) calculateTax(kenyaTax)(413202) calculateTax(tzTax)(100)
  • 59. High-order Functions - Curry. Demo029 def calculateTax(rate: BigDecimal => BigDecimal) (salary : BigDecimal ) : BigDecimal = { rate (salary) } def kenyaTax(salary : BigDecimal) = calculateTax(x => if (x > 413201) x * 0.396 else x * 0.3 )(salary) def tzTax(salary : BigDecimal) = calculateTax( x => x * 0.25)(salary) kenyaTax(413202) tzTax(100)
  • 61. Collections ❖ ❖ Concept of Collections ❖ Hierarchy of Collections - Immutable - Mutable ❖ Immutable List
  • 62. Collections. ❖ Scala supports mutable collections and immutable collections. A mutable collection can be updated or extended in place. This means you can change, add or remove elements as a side effect. Immutable collections never change. You have still operations that stimulate additions, removals, updates by creating a new collection and leave the old unchanged.
  • 65. Hierarchy of mutable Collections
  • 66. val list1 = List(1,2,3) Demo030 // Construct a List Pronounced “cons” val list2 = 1 :: 2 :: 3 :: 4 :: 5 :: Nil val list3 = List(“apples”, “oranges”,”bananas”) val list4 = List(5,5,6,6) ::: List(8,7) Immutable List
  • 67. Demo031 val list = List(4,3,0,1,2) ➔ list.head ➔ list.sortWith(_ > _) ➔ list.tail ➔ list.map(x => x * 2) ➔ list.length ➔ list.map(_ * 2) ➔ list.max ➔ list.reduce((x,y) => x + y) ➔ list.min ➔ list.filter(_ % 2 == 0) ➔ list.sum ➔ list.groupBy(x => x % 2 == 0) ➔ list.contains(2) ➔ list.drop ➔ list.reverse ImmutableList(API)
  • 68. Summary of Scala. ❖ Keep it simple ❖ Don’t pack too much in one expression ❖ Find meaningful names ❖ Prefer functional ❖ Careful with mutable objects
  • 69. Further Reading $ References. ❖ ScalaOfficial Docs ❖ Cousera-MartinOdesky ❖ CreativeScala ❖ ScalaSchool byTwitter ❖ Scala101byLightbend
  • 70. Q&A