Professional Documents
Culture Documents
Functional thinking
Lecture 1
Module 1: Basics of Scala
Module Objectives
At the end of this module, you will be able to:
Provide an introduction to Scala
Scala features
Discuss OOPs concepts within Scala compared with Java
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
Module Topics
Let us take a quick look at the topics that we will cover in this module:
Introduction to Scala
History
Features
Scala tools
REPL
Workbench
Scala constructs
Var
Val
Type inference
Type systems
Methods
Functions
Nested functions
Function literals
Placeholder functions
Partially applied functions
Scala OOPs Concepts
Defining Classes
Constructors
Class Parameters and fields
Class methods
Access modifiers
Companion Object
Case classes
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
Play Shapeless
Frameworks
Scala Slick ScalaTest
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
Scalable Concise
Object-Oriented High-Level
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
// this is Java
class MyClass {
private int index;
private String name;
public MyClass(int index, String name) { this.index = index;
this.name = name;
}
}
class MyClass(index: Int, name: String)
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
boolean nameHasUpperCase = false; // this is Java
for (int i = 0; i < name.length(); ++i) {
if (Character.isUpperCase(name.charAt(i))) {
nameHasUpperCase = true;
break;
}
}
Equivalent Scala:
val nameHasUpperCase = name.exists(_.isUpper)
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
Scala is a mixture of both object oriented and functional Java is a general purpose object oriented language.
programming.
The process of compiling source code into byte code is slow. The process of compiling source code into byte code is fast.
Scala support operator overloading. Java does not support operator overloading.
Scala supports lazy evaluation. Java does not support lazy evaluation.
Scala is not backward compatible. Java is backward compatible means the code written in the new version
can also run in older version without any error.
Any method or function present is Scala are treated like they are Java treats functions as an object.
variable.
In Scala, the code is written in compact form. In Java, the code is written in long form.
Scala variables are by default immutable type. Java variables are by default mutable type.
Scala treated everything as an instance of the class and it is more Java is less object oriented as compare to Scala due to presence of
object oriented language as compare to Java. primitives and statics.
Scala does not contain static keyword. Java contains static keyword.
In Scala, all the operations on entities are done by using method In Java, operators are treated differently and is not done with method call.
calls.
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
Questions??
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Functions and Methods
Lecture 2
Module 1: Basics of Scala
1.3.5 Methods
Declaration:
def methodName([list of parameters]):[return type] = { method body return [expr] }
def sum(a:Int, b:Int) :Int = {
a +b}
def sum(a:Int, b:Int) = a+b
sum: (a: Int, b: Int)Int
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
1.3.6 Functions
Declaration:
val functionName = ([list of type of parameters]) => [return type] = ([list of type of
parameters]) =>{ function body return [expr] }
val double : (Int => Int) = (a) => a*2
duble: Int => Int = $$Lambda$929/382522044@12f8682a
double(2)
res8: Int = 4
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
def m1(x: Int) = x + x
m1(2) // 4
Simple Function:
val f1 = (x: Int) => x + x
f1(2) // 4
f1 // Int => Int = <function1>
m1 // error: missing argument list for method m1
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
Result:
In outer
In inner
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
Sample 2:
val sumOfnos = (f: (Int) => Int, a:Int, b:Int) => sum(f(a), f(b))
sumOfnos(square, 1,2)
sumOfnos(cube, 1,2)
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
val doubler: Int => Int = _ * 2
doubler: Int => Int = <function1>
val multiplier : (Int,Int)=>Int = _*_
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
val add = (x: Int, y: Int) => x + y
val partialAdd = add(5,_:Int)
partialAdd(10)
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
1 2 3 4 5 6 7
String
Interpolation
The ’s’ string
interpolator
Creating The ‘f’
Create a Concatenating interpolator String
Strings String Length Format
String Strings The ‘raw’ Methods
Strings
interpolator
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
val greeting: String = "Hello, world!"
println( greeting )
String Length:
var palindrome = "Dot saw I was Tod";
var len = palindrome.length();
println( "String Length is : " + len );
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
var str1 = "Dot saw I was ";
var str2 = "Tod";
println("Dot " + str1 + str2);
var floatVar = 12.456
var intVar = 2000
var stringVar = "Scala!"
println(f”float value is $floatVar%2.2f ")
println(f"Int is $intVar%d ")
println(f"String is $stringVar%s ")
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
String Interpolation allows users to embed variable references directly in processed string literals.
var stringVar = "Scala!"
println(s"Hello, $stringVar")
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
Example:
s"a\nb"
res0: String = a
B
Example:raw"a\nb"
res1: String = a\nb
String Methods:
Example:
char charAt(int index)
"Ayushi".charAt(1)
res2: Char = y
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Scala Array
Amitava Choudhury
Module 1: Basics of Scala
Fixed-Length Arrays
Transforming Arrays
Common Algorithms
Deciphering Scaladoc
Multidimensional Arrays
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
val nums = new Array[Int](10)
val a = new Array[String](10)
val s = Array("Hello", "World")
s(0) = "Good Morning"
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
import scala.collection.mutable.ArrayBuffer
val b = ArrayBuffer[Int]()
// Or new ArrayBuffer[Int]
// An empty array buffer, ready to hold integers
b += 1
// ArrayBuffer(1)
// Add an element at the end with +=
b += (1, 2, 3, 5)
// ArrayBuffer(1, 1, 2, 3, 5)
// Add multiple elements at the end by enclosing them in parentheses
b ++= Array(8, 13, 21)
// ArrayBuffer(1, 1, 2, 3, 5, 8, 13, 21)
// You can append any collection with the ++= operator
b.trimEnd(5)
// ArrayBuffer(1, 1, 2)
// Removes the last five elements
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
Transforming Arrays:
val a = Array(2, 3, 5, 7, 11)
val result = for (elem <- a) yield 2 * elem
// result is Array(4, 6, 10, 14, 22)
for (elem <- a if elem % 2 == 0) yield 2 * elem
Common Algorithms:
Array(1, 7, 2, 9).sum
// 19
// Works for ArrayBuffer too
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
val matrix = Array.ofDim[Double](3, 4) // Three rows, four columns
matrix(0)(0)
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Scala Class
Lecture 5
Module 1: Basics of Scala
Object 1
Object 3
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
1.4.1 Class
Declare Class
class User
defined class User
val u = new User
u: User = User@7a8c8dcf
val isAnyRef = u.isInstanceOf[AnyRef]
isAnyRef: Boolean = true
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
1.4.1.1 Constructor
Primary constructor
class User {
println("Welcome User")
}
new User()
Welcome User
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
1.4.1.2 Constructor
class parameters
class User(name:String) {
println(name)
}
new User()
^
error: not enough arguments for constructor User: (name: String)User.
Unspecified value parameter name.
new User("user")
user
res2: User = User@25cd49a4
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
1.4.1.3 Constructor
Additional Constructors:
class User(name:String){
println(name)
def this() = {
this("Default name")
}
}
new User()
Default name
res3: User = User@7235f92b
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
class User {
var name:String =" my name"
}
defined class User
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
user.name
res14: String = testuser
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Scala object
Lecture 6
Module 1: Basics of Scala
1.4.5 Inheritance
Extending classes
class Robot
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
1.5 Inheritance
Inheriting public/protected member classes
class Robot {
def carry(weight:Int) = println(s"Carried ${weight}")
}
Carried 10
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
1.5 Inheritance
override method
class Robot {
def carry(weight:Int) = println(s"Carried ${weight}")
}
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
1.5.1 Inheritance
Override val
class Robot {
val carry= (weight:Int) => println(s"Carried ${weight}")
}
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
1.5.2 Inheritance
Constructor
class Robot(name:String) {
println(s"name ${name}")
}
class FastRobot(name:String) extends Robot((name:String)) {
println("child constructor")
}
name robot
child constructor
defined class Robot
defined class FastRobot
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Traits
Module 1: Basics of Scala
1.5.3 Traits
Following are the key details of traits:
Traits are like Java’s Syntax: trait TraitName Unlike Java, traits A class extends As in Java, trait is one
Interfaces. { body } may have concrete exactly one other that cannot be
(defined) methods. class, but many with instantiated.
any number of traits.
Syntax:
class ClassName (parameters) extends OtherClass with Trait1,..TraitN {body}
class ClassName (parameters) extends Trait1 with Trait2,..TraitN {body}
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
1.5.4 Traits
JVM supports single class inheritance(Diamond Inherit from exactly one superclass
problem) Mix-in multiple traits
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
Use extends for first trait if not extended by any other class
trait Runnable
trait Walkable
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
trait Student {
type X
def concat(m1:X,m2:X):X
val age : X
}
Abstract Members:
class Adam extends Student {
type X = Int
def concat(m1:Int , m2:Int) = m1 + m2
val age = 7
}
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Higher Order Functions
Topic 7
Module 7: Higher Order Functions
Module Objectives
At the end of this module, you will be able to:
Define the concept of higher order functions
Explain the strategy design pattern
Discuss functors and monads
Describe flatMap and monoids
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions
7.1 Higher Order Functions
What is HOF?
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions
7.1.1 Benefits of HOF
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions
7.1.2 Example for Function as a Parameter
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions
7.1.3 Example for Function as a Result
scala> multiplier(6, 5)
res0: Int = 30
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions
7.2 The Strategy Design Patterns
The Strategy Design Patterns enables to define a family of algorithms and select a specific one at runtime.
CLASS DIAGRAM
PersonApplication
Parser
- parser: Parser
+ parser: List[T]
+write (): Unit
CSVParser JsonParser
- file: String - file: String
+parse(): List[Person] +parse(): List[Person]
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions
7.2.1 The Strategy Design Patterns: Example
//Application Class
class Application[T](strategy: (String) => List[T]) {
def write(file: String): Unit = {
System.out.println(s"Got the following data ${strategy(file)}")
}}
//Function StrategyFactory
object StrategyFactory {
implicit val formats = DefaultFormats
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions
7.2.1 The Strategy Design Patterns: Example (Contd.)
object StrategyExample {
def main(args: Array[String]): Unit = {
val applicationCsv = new Application[Person](StrategyFactory("people.csv"))
val applicationJson = new Application[Person](StrategyFactory("people.json"))
Result volcom@volcom-Dell-System-XPS-L502X:~/workspace/scala-book/creational-design-patterns$ java -cp target/behavioral-1.0.0
-SNAPSHOT.jar com.ivan.nikolov.behvioral.strategy.ParserExample
Using the csv:
Got the following data List(Person(Ivan, 26, London), Person(Maria, 23, Edinburgh), Person(John, 36, New York), Person(Anna,
24, Moscow))
Using the json:
Got the following data List(Person(Ivan, 26, London), Person(Maria, 23, Edinburgh), Person(John, 36, New York), Person(Anna,
24, Moscow))
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions
7.3 Monoids
What is a Monoids?
A monoid is a purely algebraic structure, which means that it is defined only by its algebra. All
monoids must conform to the so called monoid laws.
Monoids Law:
(x <> y) <> z = x <> (y <> z) -- associativity
mempty <> x = x -- left identity
x <> mempty = x -- right identity
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions
7.4 Functors
What is a Functor?
Functor is a type class. A Functor is any data type that defines how map applies to it.
Identity: Whenever the identity function is mapped over some data, it doesn't change it. In other
words, map(x)(i => i) == x.
Composition: Multiple maps must compose together. It should make no difference if we do this
operation: x.map(i => y(i)).map(i => z(i)) or x.map(i => z(y(i))).
The map function preserves the structure of the data, for example, it does not add or remove
elements, change their order, and so on. It just changes the representation.
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions
7.5 Monads
What is a Monads?
Monad is a type class. A monad is a data type that implements the flatMap. i.e., you apply a
function that returns a wrapped value, to a wrapped value.
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions
7.5.1 Some of the Important Monads: List, Set, Option, Try and Future all Monads
Code Example:
trait User {
val child: Option[User]
}
object UserService {
def loadUser(name: String): Option[User] = { /** get user **/ }
}
val getChild = (user: User) => user.child
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions
//Step1
val f = (i: Int) => List(i - 1, i, i + 1)
//Step2
val list = List(5, 6, 7)
println(list.flatMap(f))
// prints List(4, 5, 6, 5, 6, 7, 6, 7, 8)
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions
7.6 FlatMap
FlatMap(): FlatMap does Map task and Flatten task in one call.
Example:
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions
It avoids if...else blocks
No nested for loops
No callback hell
We can write simple, elegant, readable, and neat code
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions
In a nutshell, we learnt:
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values
Semester 05
B.TECH CSE with Specialization in Big Data
Functions as First Class Values
Copyright © 2019, Xebia Group. All rights reserved. This course is licensed to UPES. release 1.0.0
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values
Module Objectives
At the end of this module, you will be able to:
* Know about first class citizen
* Understand functions as first class values
* Explain the importance and usage of the underscore with examples
* Define decorator design pattern
* List the advantages and disadvantages of decorator design pattern
* Describe the concept of currying
* Learn how to apply currying functions
* Discuss about partially applied function with examples
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values
Module Topics
Let us take a quick look at the topics that we will cover in this module:
* Functions as First Class Values
9 First class citizen
9 Samples
9 The underscore usage with examples
* The Decorator Design Pattern
9 Definition
9 Class diagram
9 Sample code
9 Pros and cons
* Currying
9 Currying functions with examples
9 Partially applied functions with examples
9 Partials without currying
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values
Here: pred is a function
scala> val pred1 = (y: Int) => y < 11 // 1
pred1: Int => Boolean = <function1>
scala> val higher: (Int => Boolean) => (Int => Boolean) = (k : Int => Boolean) =>
pred1 // 2
higher: (Int => Boolean) => (Int => Boolean) = <function1>
scala> val aFunc = higher(pred) // 3
aFunc: Int => Boolean = <function1>
scala> aFunc(12)
res4: Boolean = false
scala> aFunc(10)
res5: Boolean = true
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values
scala> matchTest(7)
res0: String = anything other than one and two
scala> matchTest(1)
res1: String = one
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values
1. What does below scala program results?
object gfg
{
def main(args: Array[String])
{
var name = (15, "chandan", true)
println(name._1)
}
}
A) chandan
B) 15
C) _15
D) _chandan
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values
2. What are private functions?
A) Functions that pass values to the methods
B) Functions that are declared within functions
C) Functions that are called by other functions
D) None of the above
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values
6.2 Currying
Currying is the technique of translating the evaluation of a function that takes multiple arguments into
evaluating a sequence of functions, each with a single argument.
Example:
scala> modBy2(10)(3)
res0: Int = 1
scala> modBy2 _
res3: Int => (Int => Int) = <function1>
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values
modBy2
param n
param d
returns a function
returns n % d
Function
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values
scala> p(2)
res6: Int = 0 // 10 % 2
scala> p(3) // 10 % 3
res7: Int = 1
Code Snippet:
scala> p(10)(4)(2)("th")
res9: String = 4th
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values
processEvens(numbersAsc) // [2, 4]
processEvens(numbersDesc) // [4, 2]
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values
Rewritten as:
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values
1. What does the below given partially applied function results?
val divide = (num: Double, den: Double) => {
num / den
}
val halfOf: (Double) => Double = divide(_, 2)
halfOf(20)
A) 20/2
B) 20.0
C) 0.5
D) 10.0
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values
2. What does the below code results?
val x:Int=>Int = 2.+
x(4)
A) 4
B) B) 2.4
C) C) 6
D) D) Int
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values
* It is also known as Wrapper.
* The decorator design pattern is a structural design pattern. A structural design pattern focuses on
the Class and Object composition.
* The purpose of the decorator design pattern: is to add functionality to objects without extending
them and without affecting the behaviour of other objects from the same class.
* Design principle: “Classes should be open for extension, but closed for modification.”
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values
Decorator
Concrete
Class Concrete
Class
Method
Method
Concrete Concrete
Decorator A Decorator B
Concrete Concrete
Class Class
Method Method
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values
* Component (VisualComponent)
* ConcreteComponent (TextView)
* Decorator
* ConcreteDecorator (BorderDecorator, ScrollDecorator)
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values
* Fewer classes than with static inheritance
* Dynamic addition/removal of decorators
* Keeps root classes simple
Disadvantages
* Proliferation of run-time instances
* Abstract decorator must provide a common interface
* Inheritance solution has an explosion of classes
* If another view were added such as streamed video view, double the number of
borders/scrollbar classes
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values
1. Among 4 participants in decorator pattern, which one defines an
object to which additional responsibilities can be attached.
A) Component
B) Concrete Component
C) Decorator
D) Concrete Decorator
2. Decorator pattern comes under which design patterns categories
of Scala?
A) Structural
B) Creational
C) Behavioral
D) Scala-specific
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values
In a nutshell, we learnt:
1. First class citizen
2. Functions as first class values
3. Importance and usage of the underscore with
examples
4. Decorator design pattern
5. Advantages and disadvantages of decorator
design pattern
6. Currying
7. Apply currying functions
8. Partially applied function with examples
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values
End of Module
Next Module 7: Higher Order Functions
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.