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

Introductiontoprogramminginscala

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
    Scala Concepts • Scalais 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 theScala 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 consoletype “Hello world!”.toUpperCase Scala Concepts
  • 9.
    Compile time andRuntime • 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 arerestrictions 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.AnyValscala.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 Workwith 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 fora 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 ❖ Ifhas 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 afunction 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 (Curlybrackets) 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 }
  • 32.
  • 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 - Itcan 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.
  • 39.
    Scala (Object Oriented) vClasses v Extends , with, override v Abstract classes v Objects, v Companion objects v Traits v Case classes
  • 40.
    Classes Demo020 Primary Constructor valinconstructor 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. Singleinheritance 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 classesare 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 singletonobject 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 classesare 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 classNotification 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.
  • 49.
    Demo012 Alonzo Church 1930 TheLambdaCalculus. ❖Theoretical foundation ❖ Pure functions - no state ❖ Not a programming language
  • 50.
    Lambda Ca lculus. VariableExpressions ƛx . x + 1 Function Application
  • 51.
    Lambda Ca lculus. Demo024 ƛx. x + 1 // Scala Translation { x : Int => x + 1 }
  • 52.
    Scala (Functional) ❖ FunctionalConcepts ❖ First class functions ❖ Anonymous functions ❖ Higher order functions
  • 53.
    Functional Concepts. Demo012 Immutability (ReferentialTransparency - 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
  • 54.
  • 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)
  • 60.
  • 61.
    Collections ❖ ❖ Concept ofCollections ❖ Hierarchy of Collections - Immutable - Mutable ❖ Immutable List
  • 62.
    Collections. ❖ Scala supportsmutable 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.
  • 63.
  • 64.
  • 65.
  • 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.