SlideShare a Scribd company logo
Introduction to Programming in
Scala
May 4th, 2017
Hungai Amuhinda
@hungai
hungaikev
hungaikev.in
hungaikevin@gmail.com
Agenda
❖ Introduction
❖ Scala Concepts
❖ OOP
❖ FP
❖ Collections
Scala:
Scala is a Java like programming
language which unifies object - oriented
and functional programming.
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
SCAVANNAH 2017
Scala Concepts
● Everything is an expression
● Expression is an instruction to execute something that
will return a value.
● An expression evaluates to a result or results in a value
SCAVANNAH 2017
Scala Class Hierarchy
scala.Any
scala.AnyVal scala.AnyRef
scala.Int
scala.Byte
scala.Boolean
scala.Char
scala.Stringscala.List
scala.Seq
scala.Map
Scala Data Types
● Boolean
● Byte
● Short
● Int
● Long
SCAVANNAH 2017
● Float
● Double
● Char
● String
Scala
Concepts(Advanced
Type System)
● Static
● Inferred (Type Inference)
● Structural
● Strong
SCAVANNAH 2017
Program with Scala (REPL)
Read Evaluate Print Loop
$ scala
Demo 03 SCAVANNAH 2017
Program with Scala (REPL)
Read Evaluate Print Loop
$ scala -Dscala.color
Demo 04 SCAVANNAH 2017
Program with Scala
(Worksheet)
Work with worksheets
● IntelliJ
● Scala IDE or Eclipse
with Scala Plugin
● Ensime
Demo 04 SCAVANNAH 2017
Program with Scala (Main)
object Demo1 {
def main (args: Array[String]): Unit = {
println(“Hello Everyone”)
println(“Welcome to today's event”)
}
}
Demo 01 SCAVANNAH 2017
Program with Scala (App)
object Demo2 extends App {
val todaysEvent = “Scavannah”
lazy val fun = (0 to 4).map(x => “fun”).mkString(“ ”)
println(“Hello world”)
println(“Welcome to ” + todaysEvent + “! n”)
}
Demo 02 SCAVANNAH 2017
Scala Concepts
SCAVANNAH 2017
❖ var, val
❖ If expressions
❖ def
❖ Block expressions
❖ While - Loops
❖ For - Loops
❖ Nested Function
❖ Recursion vs Tail recursion
❖ Pattern Matching
Scala Concepts
❖ var - variable
Something that is able or
likely to change or be
changed (Mutable)
Demo 05 SCAVANNAH 2017
❖ val - value
A value is an expression
that cannot be changed
any further (Wiki)
(Immutable)
It's similar to final in
Java
Expression with Semicolon?
val x = 5566
val y = 87
val java = “Java” ; val scala = “scala”
Demo 06 SCAVANNAH 2017
If you have multiple expressions in one
line, you will need semicolons(;).
Otherwise you don't need it.
If Expressions
❖ If has return value (expression)
❖ Scala has no ternary operator (? : )
val value = 0
val negative =
Demo 07 SCAVANNAH 2017
If (value < 0 ) true else false
Everything is an expression
def
def max (x: Int, y: Int): Int = {
If (x > y) x else y
}
Demo 08 SCAVANNAH 2017
Function body in Curly braces
Equals sign
Result type of function
Parameters
Function name
“def” starts a function definition
def
Demo 09 SCAVANNAH 2017
def max (x: Int, y: Int): Int = {
If (x > y)
return x
else
return y
}
def
Demo 010 SCAVANNAH 2017
def max (x: Int, y: Int) = {
If (x > y)
x
else
y
}
No Result type
def
Demo 011 SCAVANNAH 2017
def max (x: Int, y: Int) =
If (x > y)
x
else
y
No Curly brackets
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
SCAVANNAH 2017
Block expressions (Curly brackets)
val n = 5
val factorial = {
var result = 1
for (i <- 1 to n )
result = result * i
result
}
Demo 012 SCAVANNAH
Last expression (result) in block will be the
return value, then it will be assign result to
“factorial”
While Loop
var n = 10
var sum = 0
while (n > 0) {
sum = sum + 1
n = n - 1
}
Demo 013 SCAVANNAH
For - Loop
Demo 014 SCAVANNAH
var sum = 0
for (i <- 1 to 10) {
sum += 1
}
println(sum)
Nested Function
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
}
Demo 015 SCAVANNAH
Recursion vs Tail Recursion
Recursion vs Tail - recursion
def factorial(n : Int): BigInt = {
If (n == 0) 1
else
n * factorial(n - 1)
}
factorial (15)
factorial (150)
factorial(15000) // java.lang.StackOverflowError
Demo 016 SCAVANNAH
Recursion vs Tail - recursion
def factorial(n : Int): BigInt = {
def helpFunction(acc : Int, n: Int) : BigInt = {
If (n == 0)
acc
else
helpFunction(acc * n , n -1 )
}
helpFunction(1,n)
}
factorial(15000)
Demo 017 SCAVANNAH
“Tail - Recursion”
Recursion vs Tail - recursion
import scala.annotation.tailrec
def factorial(n : Int): BigInt = {
@tailrec
def helpFunction(acc : Int, n: Int) : BigInt = {
If (n == 0)
acc
else
helpFunction(acc * n , n -1 )
}
helpFunction(1,n)
}
factorial(15000)
Demo 018 SCAVANNAH
“You have to add a return type, when the
function is recursive”
“Add annotation is a good habit. Compiler
can check whether or not it can be
optimised. ”
Pattern Matching
❖ 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)
- It can match anything
SCAVANNAH 2017
Pattern Matching
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”)
Demo 019 SCAVANNAH
OOP
Scala (Object Oriented)
SCAVANNAH 2017
❖ Classes
❖ Extends , with, override
❖ Abstract classes
❖ Objects, Companion
objects
❖ Traits
❖ Case classes
Classes
class Employee(id : Int, val name: String, address: String, var salary: Long
)
val employee = new Employee(1,”Hungai”,”Kakamega”,40L)
Demo 020 SCAVANNAH
Primary Constructor val in constructor will give you a getter
var in constructor will give you a getter and setter
Extends, with, override.
❖ Scala is single inheritance like Java.
❖ Scala - extends = Java - extends
❖ Scala - with = Java - implements
❖ Scala - override = Java - @Override
SCAVANNAH
Single inheritance enables a derived class to inherit
properties and behaviour from a single parent class
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
SCAVANNAH
Abstract classes.
abstract class Animal (val name: String) {
val footNumber: Int
val fly : Boolean
def speaks : Unit
}
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”)
}
Demo 021 SCAVANNAH
Subclasses should be in the same file.
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
SCAVANNAH
Singleton Object.
object MathUtil {
def doubleHalfUp(precision: Int, origin: Double): Double {
val tmp = Math.pow(10,precision)
Math.round(origin * tmp)/ tmp
}
}
Demo 022 SCAVANNAH
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
SCAVANNAH
Case classes.
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)
Demo 023 SCAVANNAH
FP
The Lambda Calculus.
Demo 012 SCAVANNAH
Alonzo Church 1930
❖ Theoretical foundation
❖ Pure functions - no state
❖ Not a programming language
Lambda Calculus.
ƛx . x + 1
SCAVANNAH
ExpressionsVariable
Function Application
Lambda Calculus.
ƛx . x + 1
// Scala Translation
{ x : Int => x + 1 }
Demo 024 SCAVANNAH
Scala (Functional)
SCAVANNAH 2017
❖ Functional Concepts
❖ First class functions
❖ Anonymous functions
❖ Higher order functions
Functional Concepts.
❖ 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
Demo 012 SCAVANNAH
Anonymous functions (Lambdas).
Demo 012 SCAVANNAH
Anonymous functions.
((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)
Demo 025 SCAVANNAH
High-order Functions.
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)
Demo 026 SCAVANNAH
High-order Functions.
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)
Demo 027 SCAVANNAH
High-order Functions.
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)
Demo 028 SCAVANNAH
High-order Functions - Curry.
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)
Demo 029 SCAVANNAH
Collections
Collections
❖
SCAVANNAH
❖ 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.
SCAVANNAH
Collections Hierarchy
SCAVANNAH
Hierarchy of Immutable Collections
SCAVANNAH
Hierarchy of mutable Collections
SCAVANNAH
Immutable List
// Construct a List
val list1 = List(1,2,3)
val list2 = 1 :: 2 :: 3 :: 4 :: 5 :: Nil
val list3 = List(“apples”, “oranges”,”bananas”)
val list4 = List(5,5,6,6) ::: List(8,7)
Demo030 SCAVANNAH
Pronounced “cons”
Immutable List (API)
val list = List(4,3,0,1,2)
➔ list.head
➔ list.tail
➔ list.length
➔ list.max
➔ list.min
➔ list.sum
➔ list.contains(2)
➔ list.drop
➔ list.reverse
Demo031 SCAVANNAH
➔ list.sortWith(_ > _)
➔ list.map(x => x * 2)
➔ list.map(_ * 2)
➔ list.reduce((x,y) => x + y)
➔ list.filter(_ % 2 == 0)
➔ list.groupBy(x => x % 2 == 0)
Summary of Scala.
❖ Keep it simple
❖ Don’t pack too much in one expression
❖ Find meaningful names
❖ Prefer functional
❖ Careful with mutable objects
SCAVANNAH
Further Reading $ References.
❖ Scala Official Docs
❖ Cousera - Martin Odesky
❖ Creative Scala
❖ Scala School by Twitter
❖ Scala 101 by Lightbend
SCAVANNAH
Q & A

More Related Content

What's hot

A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
fanf42
 
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)
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
Maxim Novak
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a Neckbeard
Kelsey Gilmore-Innis
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
Jonas Bonér
 
Scala Intro
Scala IntroScala Intro
Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
Introductiontoprogramminginscala
Amuhinda Hungai
 
Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)
Omar Abdelhafith
 
Introduction To Functional Programming
Introduction To Functional ProgrammingIntroduction To Functional Programming
Introduction To Functional Programming
newmedio
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programming
Konrad Szydlo
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional Programming
Jordan Parmer
 
Quick introduction to scala
Quick introduction to scalaQuick introduction to scala
Quick introduction to scala
Mohammad Hossein Rimaz
 
Functional Programming in Scala: Notes
Functional Programming in Scala: NotesFunctional Programming in Scala: Notes
Functional Programming in Scala: Notes
Roberto Casadei
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
Tim Underwood
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Xebia IT Architects
 
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
 
Practical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan HodorogPractical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan Hodorog
3Pillar Global
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
Knoldus Inc.
 

What's hot (19)

A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
 
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
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a Neckbeard
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
Introductiontoprogramminginscala
 
Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)
 
Introduction To Functional Programming
Introduction To Functional ProgrammingIntroduction To Functional Programming
Introduction To Functional Programming
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programming
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional Programming
 
Quick introduction to scala
Quick introduction to scalaQuick introduction to scala
Quick introduction to scala
 
Functional Programming in Scala: Notes
Functional Programming in Scala: NotesFunctional Programming in Scala: Notes
Functional Programming in Scala: Notes
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
Practical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan HodorogPractical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan Hodorog
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
 

Similar to Introduction to programming in scala

Intro to Scala
 Intro to Scala Intro to Scala
Intro to Scala
manaswinimysore
 
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
 
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLab
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLabIntroduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLab
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLab
CloudxLab
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Meetu Maltiar
 
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
 
Traits inscala
Traits inscalaTraits inscala
Traits inscala
Knoldus Inc.
 
Traits in scala
Traits in scalaTraits in scala
Traits in scala
Knoldus Inc.
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
league
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
Derek Chen-Becker
 
Java, what's next?
Java, what's next?Java, what's next?
Java, what's next?
Stephan Janssen
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
Martin Odersky
 
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
 
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
 
javascript
javascript javascript
javascript
Kaya Ota
 
scala.ppt
scala.pptscala.ppt
scala.ppt
Harissh16
 
JavaScript.pptx
JavaScript.pptxJavaScript.pptx
JavaScript.pptx
Govardhan Bhavani
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Rahul Jain
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
ehsoon
 

Similar to Introduction to programming in scala (20)

Intro to Scala
 Intro to Scala Intro to Scala
Intro to Scala
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf Taiwan
 
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLab
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLabIntroduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLab
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLab
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
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
 
Traits inscala
Traits inscalaTraits inscala
Traits inscala
 
Traits in scala
Traits in scalaTraits in scala
Traits in scala
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
 
Java, what's next?
Java, what's next?Java, what's next?
Java, what's next?
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
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
 
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
 
javascript
javascript javascript
javascript
 
scala.ppt
scala.pptscala.ppt
scala.ppt
 
JavaScript.pptx
JavaScript.pptxJavaScript.pptx
JavaScript.pptx
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
 

Recently uploaded

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
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
Peter Muessig
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
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
 
SMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API ServiceSMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API Service
Yara Milbes
 
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
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
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
 
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
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
Remote DBA Services
 
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
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
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
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
Quickdice ERP
 
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdfRevolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Undress Baby
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 

Recently uploaded (20)

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
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
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
 
SMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API ServiceSMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API Service
 
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
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
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
 
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
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
 
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
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
 
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
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
 
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdfRevolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 

Introduction to programming in scala

  • 1. Introduction to Programming in Scala May 4th, 2017
  • 3. Agenda ❖ Introduction ❖ Scala Concepts ❖ OOP ❖ FP ❖ Collections
  • 4. Scala: Scala is a Java like programming language which unifies object - oriented and functional programming.
  • 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 SCAVANNAH 2017
  • 6. Scala Concepts ● Everything is an expression ● Expression is an instruction to execute something that will return a value. ● An expression evaluates to a result or results in a value SCAVANNAH 2017
  • 7. Scala Class Hierarchy scala.Any scala.AnyVal scala.AnyRef scala.Int scala.Byte scala.Boolean scala.Char scala.Stringscala.List scala.Seq scala.Map
  • 8. Scala Data Types ● Boolean ● Byte ● Short ● Int ● Long SCAVANNAH 2017 ● Float ● Double ● Char ● String
  • 9. Scala Concepts(Advanced Type System) ● Static ● Inferred (Type Inference) ● Structural ● Strong SCAVANNAH 2017
  • 10. Program with Scala (REPL) Read Evaluate Print Loop $ scala Demo 03 SCAVANNAH 2017
  • 11. Program with Scala (REPL) Read Evaluate Print Loop $ scala -Dscala.color Demo 04 SCAVANNAH 2017
  • 12. Program with Scala (Worksheet) Work with worksheets ● IntelliJ ● Scala IDE or Eclipse with Scala Plugin ● Ensime Demo 04 SCAVANNAH 2017
  • 13. Program with Scala (Main) object Demo1 { def main (args: Array[String]): Unit = { println(“Hello Everyone”) println(“Welcome to today's event”) } } Demo 01 SCAVANNAH 2017
  • 14. Program with Scala (App) object Demo2 extends App { val todaysEvent = “Scavannah” lazy val fun = (0 to 4).map(x => “fun”).mkString(“ ”) println(“Hello world”) println(“Welcome to ” + todaysEvent + “! n”) } Demo 02 SCAVANNAH 2017
  • 15. Scala Concepts SCAVANNAH 2017 ❖ var, val ❖ If expressions ❖ def ❖ Block expressions ❖ While - Loops ❖ For - Loops ❖ Nested Function ❖ Recursion vs Tail recursion ❖ Pattern Matching
  • 16. Scala Concepts ❖ var - variable Something that is able or likely to change or be changed (Mutable) Demo 05 SCAVANNAH 2017 ❖ val - value A value is an expression that cannot be changed any further (Wiki) (Immutable) It's similar to final in Java
  • 17. Expression with Semicolon? val x = 5566 val y = 87 val java = “Java” ; val scala = “scala” Demo 06 SCAVANNAH 2017 If you have multiple expressions in one line, you will need semicolons(;). Otherwise you don't need it.
  • 18. If Expressions ❖ If has return value (expression) ❖ Scala has no ternary operator (? : ) val value = 0 val negative = Demo 07 SCAVANNAH 2017 If (value < 0 ) true else false Everything is an expression
  • 19. def def max (x: Int, y: Int): Int = { If (x > y) x else y } Demo 08 SCAVANNAH 2017 Function body in Curly braces Equals sign Result type of function Parameters Function name “def” starts a function definition
  • 20. def Demo 09 SCAVANNAH 2017 def max (x: Int, y: Int): Int = { If (x > y) return x else return y }
  • 21. def Demo 010 SCAVANNAH 2017 def max (x: Int, y: Int) = { If (x > y) x else y } No Result type
  • 22. def Demo 011 SCAVANNAH 2017 def max (x: Int, y: Int) = If (x > y) x else y No Curly brackets
  • 23. 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 SCAVANNAH 2017
  • 24. Block expressions (Curly brackets) val n = 5 val factorial = { var result = 1 for (i <- 1 to n ) result = result * i result } Demo 012 SCAVANNAH Last expression (result) in block will be the return value, then it will be assign result to “factorial”
  • 25. While Loop var n = 10 var sum = 0 while (n > 0) { sum = sum + 1 n = n - 1 } Demo 013 SCAVANNAH
  • 26. For - Loop Demo 014 SCAVANNAH var sum = 0 for (i <- 1 to 10) { sum += 1 } println(sum)
  • 27. Nested Function 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 } Demo 015 SCAVANNAH
  • 28. Recursion vs Tail Recursion
  • 29. Recursion vs Tail - recursion def factorial(n : Int): BigInt = { If (n == 0) 1 else n * factorial(n - 1) } factorial (15) factorial (150) factorial(15000) // java.lang.StackOverflowError Demo 016 SCAVANNAH
  • 30. Recursion vs Tail - recursion def factorial(n : Int): BigInt = { def helpFunction(acc : Int, n: Int) : BigInt = { If (n == 0) acc else helpFunction(acc * n , n -1 ) } helpFunction(1,n) } factorial(15000) Demo 017 SCAVANNAH “Tail - Recursion”
  • 31. Recursion vs Tail - recursion import scala.annotation.tailrec def factorial(n : Int): BigInt = { @tailrec def helpFunction(acc : Int, n: Int) : BigInt = { If (n == 0) acc else helpFunction(acc * n , n -1 ) } helpFunction(1,n) } factorial(15000) Demo 018 SCAVANNAH “You have to add a return type, when the function is recursive” “Add annotation is a good habit. Compiler can check whether or not it can be optimised. ”
  • 32. Pattern Matching ❖ 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) - It can match anything SCAVANNAH 2017
  • 33. Pattern Matching 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”) Demo 019 SCAVANNAH
  • 34. OOP
  • 35. Scala (Object Oriented) SCAVANNAH 2017 ❖ Classes ❖ Extends , with, override ❖ Abstract classes ❖ Objects, Companion objects ❖ Traits ❖ Case classes
  • 36. Classes class Employee(id : Int, val name: String, address: String, var salary: Long ) val employee = new Employee(1,”Hungai”,”Kakamega”,40L) Demo 020 SCAVANNAH Primary Constructor val in constructor will give you a getter var in constructor will give you a getter and setter
  • 37. Extends, with, override. ❖ Scala is single inheritance like Java. ❖ Scala - extends = Java - extends ❖ Scala - with = Java - implements ❖ Scala - override = Java - @Override SCAVANNAH Single inheritance enables a derived class to inherit properties and behaviour from a single parent class
  • 38. 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 SCAVANNAH
  • 39. Abstract classes. abstract class Animal (val name: String) { val footNumber: Int val fly : Boolean def speaks : Unit } 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”) } Demo 021 SCAVANNAH Subclasses should be in the same file.
  • 40. 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 SCAVANNAH
  • 41. Singleton Object. object MathUtil { def doubleHalfUp(precision: Int, origin: Double): Double { val tmp = Math.pow(10,precision) Math.round(origin * tmp)/ tmp } } Demo 022 SCAVANNAH
  • 42. 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 SCAVANNAH
  • 43. Case classes. 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) Demo 023 SCAVANNAH
  • 44. FP
  • 45. The Lambda Calculus. Demo 012 SCAVANNAH Alonzo Church 1930 ❖ Theoretical foundation ❖ Pure functions - no state ❖ Not a programming language
  • 46. Lambda Calculus. ƛx . x + 1 SCAVANNAH ExpressionsVariable Function Application
  • 47. Lambda Calculus. ƛx . x + 1 // Scala Translation { x : Int => x + 1 } Demo 024 SCAVANNAH
  • 48. Scala (Functional) SCAVANNAH 2017 ❖ Functional Concepts ❖ First class functions ❖ Anonymous functions ❖ Higher order functions
  • 49. Functional Concepts. ❖ 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 Demo 012 SCAVANNAH
  • 51. Anonymous functions. ((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) Demo 025 SCAVANNAH
  • 52. High-order Functions. 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) Demo 026 SCAVANNAH
  • 53. High-order Functions. 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) Demo 027 SCAVANNAH
  • 54. High-order Functions. 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) Demo 028 SCAVANNAH
  • 55. High-order Functions - Curry. 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) Demo 029 SCAVANNAH
  • 57. Collections ❖ SCAVANNAH ❖ Concept of Collections ❖ Hierarchy of Collections - Immutable - Mutable ❖ Immutable List
  • 58. 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. SCAVANNAH
  • 60. Hierarchy of Immutable Collections SCAVANNAH
  • 61. Hierarchy of mutable Collections SCAVANNAH
  • 62. Immutable List // Construct a List val list1 = List(1,2,3) val list2 = 1 :: 2 :: 3 :: 4 :: 5 :: Nil val list3 = List(“apples”, “oranges”,”bananas”) val list4 = List(5,5,6,6) ::: List(8,7) Demo030 SCAVANNAH Pronounced “cons”
  • 63. Immutable List (API) val list = List(4,3,0,1,2) ➔ list.head ➔ list.tail ➔ list.length ➔ list.max ➔ list.min ➔ list.sum ➔ list.contains(2) ➔ list.drop ➔ list.reverse Demo031 SCAVANNAH ➔ list.sortWith(_ > _) ➔ list.map(x => x * 2) ➔ list.map(_ * 2) ➔ list.reduce((x,y) => x + y) ➔ list.filter(_ % 2 == 0) ➔ list.groupBy(x => x % 2 == 0)
  • 64. Summary of Scala. ❖ Keep it simple ❖ Don’t pack too much in one expression ❖ Find meaningful names ❖ Prefer functional ❖ Careful with mutable objects SCAVANNAH
  • 65. Further Reading $ References. ❖ Scala Official Docs ❖ Cousera - Martin Odesky ❖ Creative Scala ❖ Scala School by Twitter ❖ Scala 101 by Lightbend SCAVANNAH
  • 66. Q & A