SlideShare a Scribd company logo
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 (18)

PDF
camel-scala.pdf
Hiroshi Ono
 
PDF
Programming in Scala: Notes
Roberto Casadei
 
KEY
Scala: functional programming for the imperative mind
Sander Mak (@Sander_Mak)
 
PPT
Scala Talk at FOSDEM 2009
Martin Odersky
 
PDF
Getting Started With Scala
Xebia IT Architects
 
PDF
Functional Programming in Scala
Bassam Abd El Hameed
 
PDF
Introducing Akka
Meetu Maltiar
 
PPT
Scala
Zhiwen Guo
 
PPT
Scala in a nutshell by venkat
Venkateswaran Kandasamy
 
PDF
Google06
Zhiwen Guo
 
PDF
Scala for Java Programmers
Eric Pederson
 
PDF
Scala categorytheory
Knoldus Inc.
 
PDF
Ankara Jug - Practical Functional Programming with Scala
Ensar Basri Kahveci
 
PDF
Quick introduction to scala
Mohammad Hossein Rimaz
 
PPTX
Scala basic
Nguyen Tuan
 
PDF
scalaliftoff2009.pdf
Hiroshi Ono
 
PPTX
Joy of scala
Maxim Novak
 
PPTX
ScalaDays 2013 Keynote Speech by Martin Odersky
Typesafe
 
camel-scala.pdf
Hiroshi Ono
 
Programming in Scala: Notes
Roberto Casadei
 
Scala: functional programming for the imperative mind
Sander Mak (@Sander_Mak)
 
Scala Talk at FOSDEM 2009
Martin Odersky
 
Getting Started With Scala
Xebia IT Architects
 
Functional Programming in Scala
Bassam Abd El Hameed
 
Introducing Akka
Meetu Maltiar
 
Scala
Zhiwen Guo
 
Scala in a nutshell by venkat
Venkateswaran Kandasamy
 
Google06
Zhiwen Guo
 
Scala for Java Programmers
Eric Pederson
 
Scala categorytheory
Knoldus Inc.
 
Ankara Jug - Practical Functional Programming with Scala
Ensar Basri Kahveci
 
Quick introduction to scala
Mohammad Hossein Rimaz
 
Scala basic
Nguyen Tuan
 
scalaliftoff2009.pdf
Hiroshi Ono
 
Joy of scala
Maxim Novak
 
ScalaDays 2013 Keynote Speech by Martin Odersky
Typesafe
 

Similar to Introductiontoprogramminginscala (20)

PDF
Introduction to Scala for JCConf Taiwan
Jimin Hsieh
 
PPTX
Intro to Scala
manaswinimysore
 
PPTX
Principles of functional progrmming in scala
ehsoon
 
PPTX
Scala for curious
Tim (dev-tim) Zadorozhniy
 
PDF
Meet scala
Wojciech Pituła
 
PDF
Programming in scala - 1
Mukesh Kumar
 
PPTX
Scala training workshop 02
Nguyen Tuan
 
PPTX
Scala final ppt vinay
Viplav Jain
 
ODP
Scala ntnu
Alf Kristian Støyle
 
PPTX
Introduction to Scala
Rahul Jain
 
ODP
Knolx Session : Built-In Control Structures in Scala
Ayush Mishra
 
PDF
Introduction to Scala : Clueda
Andreas Neumann
 
PPTX
Scala, Play 2.0 & Cloud Foundry
Pray Desai
 
PDF
Scala in Practice
Francesco Usai
 
PPTX
Introduction to Scala
Viyaan Jhiingade
 
PDF
Scala Quick Introduction
Damian Jureczko
 
PDF
Functional programming in Scala
datamantra
 
PPTX
Scala Introduction
Constantine Nosovsky
 
PPTX
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Andrew Phillips
 
PPTX
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
Andrew Phillips
 
Introduction to Scala for JCConf Taiwan
Jimin Hsieh
 
Intro to Scala
manaswinimysore
 
Principles of functional progrmming in scala
ehsoon
 
Scala for curious
Tim (dev-tim) Zadorozhniy
 
Meet scala
Wojciech Pituła
 
Programming in scala - 1
Mukesh Kumar
 
Scala training workshop 02
Nguyen Tuan
 
Scala final ppt vinay
Viplav Jain
 
Introduction to Scala
Rahul Jain
 
Knolx Session : Built-In Control Structures in Scala
Ayush Mishra
 
Introduction to Scala : Clueda
Andreas Neumann
 
Scala, Play 2.0 & Cloud Foundry
Pray Desai
 
Scala in Practice
Francesco Usai
 
Introduction to Scala
Viyaan Jhiingade
 
Scala Quick Introduction
Damian Jureczko
 
Functional programming in Scala
datamantra
 
Scala Introduction
Constantine Nosovsky
 
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Andrew Phillips
 
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
Andrew Phillips
 
Ad

Recently uploaded (20)

PPTX
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
PPT
MergeSortfbsjbjsfk sdfik k
RafishaikIT02044
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PDF
Salesforce CRM Services.VALiNTRY360
VALiNTRY360
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PDF
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
PPTX
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
 
PPTX
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
PPTX
MiniTool Power Data Recovery Full Crack Latest 2025
muhammadgurbazkhan
 
PPTX
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
DOCX
Import Data Form Excel to Tally Services
Tally xperts
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
PDF
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
PDF
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
PPTX
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PDF
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
PPTX
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
MergeSortfbsjbjsfk sdfik k
RafishaikIT02044
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Salesforce CRM Services.VALiNTRY360
VALiNTRY360
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
 
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
MiniTool Power Data Recovery Full Crack Latest 2025
muhammadgurbazkhan
 
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
Import Data Form Excel to Tally Services
Tally xperts
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
Ad

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(“[email protected]”,”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