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

camel-scala.pdf
camel-scala.pdfcamel-scala.pdf
camel-scala.pdf
Hiroshi Ono
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
Roberto Casadei
 
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
Sander Mak (@Sander_Mak)
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
Martin Odersky
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Xebia IT Architects
 
Functional Programming in Scala
Functional Programming in ScalaFunctional Programming in Scala
Functional Programming in Scala
Bassam Abd El Hameed
 
Introducing Akka
Introducing AkkaIntroducing Akka
Introducing Akka
Meetu Maltiar
 
Scala
ScalaScala
Scala
Zhiwen Guo
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
Venkateswaran Kandasamy
 
Google06
Google06Google06
Google06
Zhiwen Guo
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
Eric Pederson
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
Knoldus Inc.
 
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
Ensar Basri Kahveci
 
Quick introduction to scala
Quick introduction to scalaQuick introduction to scala
Quick introduction to scala
Mohammad Hossein Rimaz
 
Scala basic
Scala basicScala basic
Scala basic
Nguyen Tuan
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
Maxim Novak
 
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
Typesafe
 

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

Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf Taiwan
Jimin Hsieh
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Meetu Maltiar
 
Scala on Android
Scala on AndroidScala on Android
Scala on Android
Jakub Kahovec
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
Neelkanth Sachdeva
 
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
 
Intro to Scala
 Intro to Scala Intro to Scala
Intro to Scala
manaswinimysore
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
league
 
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
Miles Sabin
 
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
 
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
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
Tim (dev-tim) Zadorozhniy
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
Knoldus Inc.
 
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
Isaias Barroso
 
Scala ntnu
Scala ntnuScala ntnu
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
Michael Stal
 
Traits inscala
Traits inscalaTraits inscala
Traits inscala
Knoldus Inc.
 
Traits in scala
Traits in scalaTraits in scala
Traits in scala
Knoldus Inc.
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Rahul Jain
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010
JUG Lausanne
 

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

Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
Remote DBA Services
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptxLORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
lorraineandreiamcidl
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
kalichargn70th171
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
rodomar2
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
Green Software Development
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
SOCRadar
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
Hironori Washizaki
 
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise EditionWhy Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Envertis Software Solutions
 

Recently uploaded (20)

Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptxLORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
 
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise EditionWhy Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
 

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