SlideShare a Scribd company logo
Abdhesh Kumar
abdhesh@knoldus.com
Extractors & Implicit conversions
Extractors
update method
Implicit conversions, parameters and implicit context
Extractor
Pattern Matching???
object ListExtractor {
val xs = 3 :: 6 :: 12 :: Nil
xs match {
case List(a, b) => a * b
case List(a, b, c) => a + b + c
case _ => 0
}
}
object knolx {
val head :: tail = List(1, 2, 3)
}
Extractor
If you have some student data, each is "B123456, Bob, New Delhi"
format, you want to Obtained a student number, name and place of birth
information
object Student {
def separate(s: String) = {
val parts = s.split(",")
if (parts.length == 3) Some((parts(0), parts(1), parts(2))
else None
}
}
object StudentApp extends App {
val student = Student.separate("B123456, Bob, New Delhi")
student match {
case Some((number, name, addr)) =>
println(s"Student Information:::name=$name,
number=$number and address=$addr")
case None => println("Wrong data found")
}
}
val students = List(
"B123456,Ankit,New Delhi",
"B123455,Anand,New Delhi",
"B123454,Satendra,New Delhi")
This is possible??
val Student(number, name, addr) = "B123456, Bob, New Delhi"
Extractor (unapply)
case class Student(number: String, name: String, address: String)
val students = List(
"B123456,Ankit,New Delhi",
"B123455,Anand,New Delhi",
"B123454,Satendra,New Delhi")
val info: List[Student] = ???
Extractor (unapply)
def unapply(object: S): Option[T]
object Student {
def unapply(str: String): Option[(String, String, String)] = {
val parts = str.split(",")
if (parts.length == 3) Some(parts(0), parts(1), parts(2))
else None
}
}
Extractor (unapply)
object StudentApp extends App {
val Student(number, name, addr) = "B123456, Bob, New Delhi"
println(s"Student information=${(number, name, address)}")
}
Extractor (unapply)
object StudentApp extends App {
val students = List(
"B123456,Ankit,New Delhi",
"B123455,Anand,New Delhi",
"B123454,Satendra,New Delhi")
val result: List[Student] = students collect {
case Student(number, name, address) => Student(number, name, address)
}
println(result)
}
Extractor (unapply)
case class Student(number: String, name: String, address: String)
object Student {
def unapply(str: String): Option[(String, String, String)] = {
val parts = str.split(",")
if (parts.length == 3) Some(parts(0), parts(1), parts(2)) else None
}
}
object Utility {
def extractInformation(data: List[String]): List[Student] = {
def extractInfo(extractedInfo: List[Student], result: List[String]): List[Student] = {
result match {
case Student(number, name, address) :: tail =>
extractInfo(extractedInfo :+ Student(number, name, address), tail)
case Nil => extractedInfo
case _ :: tail => extractInfo(extractedInfo, tail)
}
}
extractInfo(List[Student](), data)
}
}
Safe Extractor (unapply)
object EMail {
// The extraction method (mandatory)
def unapply(str: String): Option[(String, String)] = {
val parts = str split "@"
if (parts.length == 2) Some(parts(0), parts(1)) else None
}
}
object SafeExtractor extends App {
val any: Any = "abdhehs@knoldus.com"
any match {
case EMail(user, domain) => println(s"Matched:::${(user, domain)}")
case _ => println("Not Mathed")
}
}
Extractor (unapply)
object GivenNames {
def unapply(name: String): Option[(String, String)] = {
val names = name.trim.split(",")
if (names.length >= 2) Some((names(1), names(0))) else None
}
}
object ExtractNames extends App {
def greetWithFirstName(name: String) = name match {
case GivenNames(firstName, _) => "Good evening, " + firstName + "!"
case _ => "Welcome! Please make sure to fill in your name!"
}
val information = "Kumar,Abdhesh,New Delhi"
val result = greetWithFirstName(information)
println(result)
}
object UserName {
def unapplySeq(email: String): Option[Seq[String]] = {
val parts = email split ","
if (parts.nonEmpty) Some(parts)
else None
}
}
object UserNameApp extends App {
val name = "Kumar,Abdhesh,New Delhi"
name match {
case UserName(lastName, firstName, _*) =>
println(s"First Name=$firstName and Last Name=$lastName")
case _ => println("Not Matched")
}
val UserName(lastName, firstName, others @ _*) = name
}
Extract sequences (unapplySeq)
object UserName {
def unapplySeq(email: String): Option[Seq[String]] = {
val parts = email split ","
if (parts.nonEmpty) Some(parts)
else None
}
}
object UserNameApp extends App {
val name = "Kumar,Abdhesh,New Delhi"
name match {
case UserName(lastName, firstName, others @ _*) =>
println(s"First Name=$firstName and Last Name=$lastName")
case _ => println("Not Matched")
}
}
Extract sequences (unapplySeq)..
Wildcard operators

If you only care about the first variable you can use _* to reference the
rest of the sequence that you don't care about

using @ _* we can get the rest of the sequence assigned to others
Combining fixed and variable parameter
extraction
Sometimes, you have certain fixed values to be extracted that you know
about at compile time, plus an additional optional sequence of values.
def unapplySeq(object: S): Option[(T1, .., Tn-1, Seq[T])]
*unapplySeq can also return an Option of a TupleN , where the last element of the tuple
must be the
Combining fixed and variable parameter
extraction
object Names {
def unapplySeq(name: String): Option[(String, String, Seq[String])] = {
val names = name.trim.split(" ")
if (names.size < 2) None
else Some((names.last, names.head, names.drop(1).dropRight(1)))
}
}
object MixedExtractor {
def greet(fullName: String) = fullName match {
case Names(lastName, firstName, _*) => "Good morning, " + firstName +
" " + lastName + "!"
Case _ => "Welcome! Please make sure to fill in your name!"
}
}
A Boolean Extractor
object StudentBool {
def unapply(student: String): Boolean = student.contains("Allahabad")
}
object BooleanExtractorApp extends App {
val name = "B123456,Ankit,Allahabad"
name match {
case studentI @ StudentBool() => println(studentI)
case _ => println("Not Found")
}
}
A Boolean Extractor
object StudentBool {
def unapply(student: String): Boolean =
student.contains("Allahabad")
}
object BooleanExtractorApp extends App {
val students = List(
"B123455,Anand,New Delhi",
"B123454,Satendra,New Delhi",
"B123456,Ankit,Allahabad")
students collect {
case std @ StudentBool() => std
}
}
Instances of a class with unapply method
class Splitter(sep: Char) {
def unapply(v: String): Option[(String, String)] = (v indexOf sep) match {
case x if (x > 0) => Some((v take x, v drop x + 1))
case _ => None
}
}
object SimpleExtractor extends App {
val SplitOnComma = new Splitter(',')
"1,2" match { case SplitOnComma(one, two) => println(one, two) }
//All extractors can also be used in assignments
val SplitOnComma(one, two) = "1,2"
}
Every Regex object in Scala has an
extractor
object RegexExtractor extends App {
val Decimal = new Regex("""(-)?(d+)(.d*)?""")
val input = "for -1.0 to 99 by 3"
for (s <- Decimal findAllIn input) println _
val dec = Decimal findFirstIn input
val Decimal(sign, integerpart, decimalpart) = "-1.23"
println((sign, integerpart, decimalpart))
val Decimal(signI, integerpartI, decimalpartI) = "32323"
// Regex to split a date in the format Y/M/D.
val regex = "(d+)/(d+)/(d+)".r
val regex(year, month, day) = "2010/1/13"
}
Extractor Rules

unapply () method called extractor

unapply can’t be overloaded (because it always takes the the same
argument).
Implicts
Where Implicits are Tried
Implicits are used in three places in Scala
○ Conversions to an expected type
■ For objects passed in to a function that expects a different type
Where Implicits are Tried..
○ Conversions of the receiver of a selection
■ For when methods are called on an object that doesn't have
those methods defined, but an implicit conversion does
(e.g. -> method for maps)
Where Implicits are Tried...
○ Implicit Parameters
■ Provide more information to a called method about what the
caller wants
■ Especially useful with generic functions
Rules for Implicit
Marking Rule: Only definitions marked implicit are available
The implicit keyword is used to mark which declarations the
compiler may use as implicits.
implicit def intToString(x: Int) = x.toString
def dbl2Str(d: Double): String = d.toString // ignored
Rules for Implicit
Scope Rule: An inserted implicit conversion must be in
scope as a single identifier, or be associated with the source
or target type of the conversion.

The Scala compiler will only consider implicit conversions that are in
scope

The compiler will also look for implicit definitions in the companion object
of
the source or expected target types of the conversion
Rules for Implicit
Non-Ambiguity Rule: An implicit conversion is only inserted if
there is no other possible conversion to insert.
One-at-a-time Rule: Only one implicit is tried.
The compiler will never rewrite x + y to convert1(convert2(x)) + y.
Rules for Implicit
Explicits-First Rule: Whenever code type checks as it is written,
no implicits are attempted
Naming Conventions for Implicit

Can have arbitrary names

The compiler doesn't care

Naming should be chosen for two considerations:

Explicit usage of the conversion

Explicit importing into scope for the conversion
Implicits Methods
The idea is to be able to extend functionality of an existing class with new
methods in a type safe manner.
Implicits Methods
class MyInteger(val i: Int) {
def myNewMethod = println("hello from myNewMethod")
def inc = new MyInteger(i + 1)
}
object MyIntegerConvertor {
implicit def int2MyInt(i: Int) = new MyInteger(i)
implicit def myInt2Int(mI: MyInteger) = mI.i
}
object ImplicitMethods extends App {
import MyIntegerConvertor._
val result = 1.myNewMethod
val inc = 2.inc
def takesInt(i: Int) = println(i)
takesInt(inc)
takesInt(5.inc)
}
Implicits Parameters
It is similar to default parameters, but it has a different
mechanism for finding the “default” value.
The implicit parameter is a parameter to method or constructor that is
marked as implicit.
This means if a parameter value is not mentioned then the
compiler will search for an “implicit” value defined within a scope.
Implicits Parameters
object ImplicitParameters {
def p(implicit i: Int) = print(i)
def sayThings(implicit args: List[Any]) =
args.foreach(println(_))
}
object ImplicitParametersApp extends App {
import ImplicitParameters._
implicit val nothingNiceToSay: List[Any] = Nil
sayThings
implicit val v = 2
}
Implicits Parameters
Matching implicit arguments

Implicits are totally typesafe, and are selected based on the static type of
the
arguments. Here are some examples to show how things work.
def speakImplicitly(implicit greeting: String) = println(greeting)
implicit val aUnit = ()
speakImplicitly //no implicit argument matching parameter type
String was found.
Implicits Parameters
Implicit arguments of subtypes
def sayThings(implicit args: List[Any]) = args.foreach(println(_))
implicit val nothingNiceToSay: List[Any] = Nil
sayThings
implicit val hello: List[String] = List("Hello world");
sayThings
Implicits Parameters
/**
One important restriction is that there can only be a single
implicit keyword per method. It must be at the start of a
parameter list (which also makes all values of that parameter
list be implicit).
*/
def pp(a: Int)(implicit i: Int) = println(a, i)
//both i and b are implicit
def pp(a: Int)(implicit i: Int, b: Long) = println(a, i, b)
def pp(implicit i: Int, b: Long) = println(i, b)
def pp(implicit i: Int, b: Long*) = println(i, b)
def pp(b: Long*)(implicit i: Int) = println(i, b)
/When you have a implicit keyword in the first of parameter list, all the
parameters in this list are implicit!
Implicit Classes

Must take exactly one parameter (Though can have a
second, implicit parameter list)

Must be defined where a method could be defined (not at top
level)

Generated method will have same name as the class, so can
be imported together.
Implicit Classes
object Helpers {
implicit class IntWithTimes(x: Int) {
def times[A](f: => A): Unit = {
def loop(current: Int): Unit =
if (current > 0) {
f
loop(current - 1)
}
loop(x)
}
}
}
object ImpliciClasses {
import Helpers._
5 times println("HI")
}
Implicit Classes
Implicit classes have the following restrictions:
1. They must be defined inside of another trait / class / object .
2.They may only take one non­implicit argument in their constructor.
3. There may not be any method, member or object in scope with the same name as the
implicit class.
Sort User Defined Objects
case class Employee(id: Int, firstName: String, lastName:
String)
object Employee {
implicit def orderingByName[A <: Employee]: Ordering[A] =
Ordering.by(e => e.firstName)
val orderingById: Ordering[Employee] = Ordering.by(e => e.id)
}
Sort User Defined Objects
object ImplicitBox extends App {
val employees = List(
Employee(1, "A", "AA"),
Employee(4, "D", "AA"),
Employee(5, "E", "EE"),
Employee(2, "B", "BB"),
Employee(3, "C", "CC"))
val sortByName = employees.sorted
println(s"Sort Employee by name=${sortByName}")
val sortById = employees.sorted(Employee.orderingById)
println(s"Sort Employee by Id=${sortById}")
}
How can I chain/nest implicit conversions?
Scala does not allow two such implicit conversions taking
place, however, so one cannot got from A to C using an
implicit A to B and another implicit B to C .
Is there a way around this restriction?
Scala has a restriction on automatic conversions to add a
method, which is that it won’t apply more than one
conversion in trying to find methods.
How can I chain/nest implicit conversions?
object T1 {
implicit def toA(n: Int): A = new A(n)
implicit def aToB(a: A): B = new B(a.n, a.n)
implicit def bToC(b: B): C = new C(b.m, b.n, b.m + b.n)
// won't work
//println(5.total)
//println(new A(5).total)
// works
println(new B(5, 5).total)
println(new C(5, 5, 10).total)
}
How can I chain/nest implicit conversions?
// def m[A <% B](m: A) is the same thing as
// def m[A](m: A)(implicit ev: A => B)
object T2 extends App {
implicit def toA(n: Int): A = new A(n)
implicit def aToB[A1 <% A](a: A1): B = new B(a.n, a.n)
implicit def bToC[B1 <% B](b: B1): C = new C(b.m, b.n, b.m + b.n)
// works
println(5.total)
println(new A(5).total)
println(new B(5, 5).total)
println(new C(5, 5, 10).total)
}
update method
a(x) = y, the compiler interprets this to as a.update(x, y)
class PhonebookExpend {
private val numbers = scala.collection.mutable.Map[String, (Int, Int)]()
def apply(name: String) = numbers(name)
def update(name: String, number: (Int, Int)) = numbers(name) = number
}
object EchoUpdate extends App {
val e = new Echo()
e("hello", "hi") = "knoldus"
//e("hello") = ("salut", "bonjour")
val book2 = new PhonebookExpend()
book2("jesse") = (123, 4567890)
val (areaCode, local) = book2("jesse")
}
References
http://daily­scala.blogspot.in/
Programming in Scala Book
Thanks.

More Related Content

What's hot

Java Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream APIJava Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream API
Svetlin Nakov
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
Reem Alattas
 
The Ring programming language version 1.4 book - Part 9 of 30
The Ring programming language version 1.4 book - Part 9 of 30The Ring programming language version 1.4 book - Part 9 of 30
The Ring programming language version 1.4 book - Part 9 of 30
Mahmoud Samir Fayed
 
Python programming : Abstract classes interfaces
Python programming : Abstract classes interfacesPython programming : Abstract classes interfaces
Python programming : Abstract classes interfaces
Emertxe Information Technologies Pvt Ltd
 
Generics in .NET, C++ and Java
Generics in .NET, C++ and JavaGenerics in .NET, C++ and Java
Generics in .NET, C++ and Java
Sasha Goldshtein
 
Functional object
Functional objectFunctional object
Functional object
ruchijindal87
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
malaybpramanik
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
Svetlin Nakov
 
Lec2
Lec2Lec2
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
Intro C# Book
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and Classes
Svetlin Nakov
 
The Ring programming language version 1.3 book - Part 24 of 88
The Ring programming language version 1.3 book - Part 24 of 88The Ring programming language version 1.3 book - Part 24 of 88
The Ring programming language version 1.3 book - Part 24 of 88
Mahmoud Samir Fayed
 
Array in Java
Array in JavaArray in Java
Array in Java
Shehrevar Davierwala
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
bhavesh prakash
 
C++ Template
C++ TemplateC++ Template
C++ Template
Saket Pathak
 
Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>
Svetlin Nakov
 
Lec2
Lec2Lec2
Java arrays
Java    arraysJava    arrays
Java arrays
Mohammed Sikander
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
Knoldus Inc.
 
An Introduction to Part of C++ STL
An Introduction to Part of C++ STLAn Introduction to Part of C++ STL
An Introduction to Part of C++ STL
乐群 陈
 

What's hot (20)

Java Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream APIJava Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream API
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
 
The Ring programming language version 1.4 book - Part 9 of 30
The Ring programming language version 1.4 book - Part 9 of 30The Ring programming language version 1.4 book - Part 9 of 30
The Ring programming language version 1.4 book - Part 9 of 30
 
Python programming : Abstract classes interfaces
Python programming : Abstract classes interfacesPython programming : Abstract classes interfaces
Python programming : Abstract classes interfaces
 
Generics in .NET, C++ and Java
Generics in .NET, C++ and JavaGenerics in .NET, C++ and Java
Generics in .NET, C++ and Java
 
Functional object
Functional objectFunctional object
Functional object
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
 
Lec2
Lec2Lec2
Lec2
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and Classes
 
The Ring programming language version 1.3 book - Part 24 of 88
The Ring programming language version 1.3 book - Part 24 of 88The Ring programming language version 1.3 book - Part 24 of 88
The Ring programming language version 1.3 book - Part 24 of 88
 
Array in Java
Array in JavaArray in Java
Array in Java
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
C++ Template
C++ TemplateC++ Template
C++ Template
 
Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>
 
Lec2
Lec2Lec2
Lec2
 
Java arrays
Java    arraysJava    arrays
Java arrays
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
 
An Introduction to Part of C++ STL
An Introduction to Part of C++ STLAn Introduction to Part of C++ STL
An Introduction to Part of C++ STL
 

Viewers also liked

Type-Safe MongoDB query (Lift Rogue query)
Type-Safe MongoDB query (Lift Rogue query)Type-Safe MongoDB query (Lift Rogue query)
Type-Safe MongoDB query (Lift Rogue query)
Knoldus Inc.
 
Brief introduction of Slick
Brief introduction of SlickBrief introduction of Slick
Brief introduction of Slick
Knoldus Inc.
 
Evolution and Scaling of MongoDB Management Service Running on MongoDB
Evolution and Scaling of MongoDB Management Service Running on MongoDBEvolution and Scaling of MongoDB Management Service Running on MongoDB
Evolution and Scaling of MongoDB Management Service Running on MongoDB
MongoDB
 
Using Websockets in Play !
Using Websockets in Play !Using Websockets in Play !
Using Websockets in Play !
Knoldus Inc.
 
Scala with MongoDB
Scala with MongoDBScala with MongoDB
Scala with MongoDB
Abdhesh Kumar
 
Scala with mongodb
Scala with mongodbScala with mongodb
Scala with mongodb
Knoldus Inc.
 
Real time Analytics with Apache Kafka and Apache Spark
Real time Analytics with Apache Kafka and Apache SparkReal time Analytics with Apache Kafka and Apache Spark
Real time Analytics with Apache Kafka and Apache Spark
Rahul Jain
 

Viewers also liked (7)

Type-Safe MongoDB query (Lift Rogue query)
Type-Safe MongoDB query (Lift Rogue query)Type-Safe MongoDB query (Lift Rogue query)
Type-Safe MongoDB query (Lift Rogue query)
 
Brief introduction of Slick
Brief introduction of SlickBrief introduction of Slick
Brief introduction of Slick
 
Evolution and Scaling of MongoDB Management Service Running on MongoDB
Evolution and Scaling of MongoDB Management Service Running on MongoDBEvolution and Scaling of MongoDB Management Service Running on MongoDB
Evolution and Scaling of MongoDB Management Service Running on MongoDB
 
Using Websockets in Play !
Using Websockets in Play !Using Websockets in Play !
Using Websockets in Play !
 
Scala with MongoDB
Scala with MongoDBScala with MongoDB
Scala with MongoDB
 
Scala with mongodb
Scala with mongodbScala with mongodb
Scala with mongodb
 
Real time Analytics with Apache Kafka and Apache Spark
Real time Analytics with Apache Kafka and Apache SparkReal time Analytics with Apache Kafka and Apache Spark
Real time Analytics with Apache Kafka and Apache Spark
 

Similar to Extractors & Implicit conversions

An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
Mohsen Zainalpour
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
Tom Flaherty
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
ehsoon
 
Object Oriented Programming Using C++: C++ STL Programming.pptx
Object Oriented Programming Using C++: C++ STL Programming.pptxObject Oriented Programming Using C++: C++ STL Programming.pptx
Object Oriented Programming Using C++: C++ STL Programming.pptx
RashidFaridChishti
 
Arrays
ArraysArrays
Arrays
Komal Singh
 
Scala by Luc Duponcheel
Scala by Luc DuponcheelScala by Luc Duponcheel
Scala by Luc Duponcheel
Stephan Janssen
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
Meetu Maltiar
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
Knoldus Inc.
 
Arrays and function basic c programming notes
Arrays and function basic c programming notesArrays and function basic c programming notes
Arrays and function basic c programming notes
GOKULKANNANMMECLECTC
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
Eelco Visser
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
Tomer Gabel
 
Xm lparsers
Xm lparsersXm lparsers
Xm lparsers
Suman Lata
 
ScalaLanguage_ch_4_5.pptx
ScalaLanguage_ch_4_5.pptxScalaLanguage_ch_4_5.pptx
ScalaLanguage_ch_4_5.pptx
jkapardhi
 
Scala taxonomy
Scala taxonomyScala taxonomy
Scala taxonomy
Radim Pavlicek
 
Intro to C# - part 2.pptx emerging technology
Intro to C# - part 2.pptx emerging technologyIntro to C# - part 2.pptx emerging technology
Intro to C# - part 2.pptx emerging technology
worldchannel
 
C++11 - STL Additions
C++11 - STL AdditionsC++11 - STL Additions
C++11 - STL Additions
GlobalLogic Ukraine
 
Op ps
Op psOp ps
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
Tomasz Wrobel
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
Maulen Bale
 
Introducing Pattern Matching in Scala
 Introducing Pattern Matching  in Scala Introducing Pattern Matching  in Scala
Introducing Pattern Matching in Scala
Ayush Mishra
 

Similar to Extractors & Implicit conversions (20)

An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
 
Object Oriented Programming Using C++: C++ STL Programming.pptx
Object Oriented Programming Using C++: C++ STL Programming.pptxObject Oriented Programming Using C++: C++ STL Programming.pptx
Object Oriented Programming Using C++: C++ STL Programming.pptx
 
Arrays
ArraysArrays
Arrays
 
Scala by Luc Duponcheel
Scala by Luc DuponcheelScala by Luc Duponcheel
Scala by Luc Duponcheel
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
 
Arrays and function basic c programming notes
Arrays and function basic c programming notesArrays and function basic c programming notes
Arrays and function basic c programming notes
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
Xm lparsers
Xm lparsersXm lparsers
Xm lparsers
 
ScalaLanguage_ch_4_5.pptx
ScalaLanguage_ch_4_5.pptxScalaLanguage_ch_4_5.pptx
ScalaLanguage_ch_4_5.pptx
 
Scala taxonomy
Scala taxonomyScala taxonomy
Scala taxonomy
 
Intro to C# - part 2.pptx emerging technology
Intro to C# - part 2.pptx emerging technologyIntro to C# - part 2.pptx emerging technology
Intro to C# - part 2.pptx emerging technology
 
C++11 - STL Additions
C++11 - STL AdditionsC++11 - STL Additions
C++11 - STL Additions
 
Op ps
Op psOp ps
Op ps
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
 
Introducing Pattern Matching in Scala
 Introducing Pattern Matching  in Scala Introducing Pattern Matching  in Scala
Introducing Pattern Matching in Scala
 

More from Knoldus Inc.

Terratest - Automation testing of infrastructure
Terratest - Automation testing of infrastructureTerratest - Automation testing of infrastructure
Terratest - Automation testing of infrastructure
Knoldus Inc.
 
Getting Started with Apache Spark (Scala)
Getting Started with Apache Spark (Scala)Getting Started with Apache Spark (Scala)
Getting Started with Apache Spark (Scala)
Knoldus Inc.
 
Secure practices with dot net services.pptx
Secure practices with dot net services.pptxSecure practices with dot net services.pptx
Secure practices with dot net services.pptx
Knoldus Inc.
 
Distributed Cache with dot microservices
Distributed Cache with dot microservicesDistributed Cache with dot microservices
Distributed Cache with dot microservices
Knoldus Inc.
 
Introduction to gRPC Presentation (Java)
Introduction to gRPC Presentation (Java)Introduction to gRPC Presentation (Java)
Introduction to gRPC Presentation (Java)
Knoldus Inc.
 
Using InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in JmeterUsing InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in Jmeter
Knoldus Inc.
 
Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)
Knoldus Inc.
 
Stakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) PresentationStakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) Presentation
Knoldus Inc.
 
Introduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) PresentationIntroduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) Presentation
Knoldus Inc.
 
Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)
Knoldus Inc.
 
Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)
Knoldus Inc.
 
Clean Code in Test Automation Differentiating Between the Good and the Bad
Clean Code in Test Automation  Differentiating Between the Good and the BadClean Code in Test Automation  Differentiating Between the Good and the Bad
Clean Code in Test Automation Differentiating Between the Good and the Bad
Knoldus Inc.
 
Integrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test AutomationIntegrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test Automation
Knoldus Inc.
 
State Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptxState Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptx
Knoldus Inc.
 
Authentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptxAuthentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptx
Knoldus Inc.
 
OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)
Knoldus Inc.
 
Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
Knoldus Inc.
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Knoldus Inc.
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
Knoldus Inc.
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
Knoldus Inc.
 

More from Knoldus Inc. (20)

Terratest - Automation testing of infrastructure
Terratest - Automation testing of infrastructureTerratest - Automation testing of infrastructure
Terratest - Automation testing of infrastructure
 
Getting Started with Apache Spark (Scala)
Getting Started with Apache Spark (Scala)Getting Started with Apache Spark (Scala)
Getting Started with Apache Spark (Scala)
 
Secure practices with dot net services.pptx
Secure practices with dot net services.pptxSecure practices with dot net services.pptx
Secure practices with dot net services.pptx
 
Distributed Cache with dot microservices
Distributed Cache with dot microservicesDistributed Cache with dot microservices
Distributed Cache with dot microservices
 
Introduction to gRPC Presentation (Java)
Introduction to gRPC Presentation (Java)Introduction to gRPC Presentation (Java)
Introduction to gRPC Presentation (Java)
 
Using InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in JmeterUsing InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in Jmeter
 
Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)
 
Stakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) PresentationStakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) Presentation
 
Introduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) PresentationIntroduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) Presentation
 
Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)
 
Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)
 
Clean Code in Test Automation Differentiating Between the Good and the Bad
Clean Code in Test Automation  Differentiating Between the Good and the BadClean Code in Test Automation  Differentiating Between the Good and the Bad
Clean Code in Test Automation Differentiating Between the Good and the Bad
 
Integrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test AutomationIntegrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test Automation
 
State Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptxState Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptx
 
Authentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptxAuthentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptx
 
OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)
 
Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 

Recently uploaded

TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
Edge AI and Vision Alliance
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
IndexBug
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
Mariano Tinti
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
Claudio Di Ciccio
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 

Recently uploaded (20)

TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 

Extractors & Implicit conversions

  • 2. Extractors update method Implicit conversions, parameters and implicit context
  • 3. Extractor Pattern Matching??? object ListExtractor { val xs = 3 :: 6 :: 12 :: Nil xs match { case List(a, b) => a * b case List(a, b, c) => a + b + c case _ => 0 } } object knolx { val head :: tail = List(1, 2, 3) }
  • 4. Extractor If you have some student data, each is "B123456, Bob, New Delhi" format, you want to Obtained a student number, name and place of birth information
  • 5. object Student { def separate(s: String) = { val parts = s.split(",") if (parts.length == 3) Some((parts(0), parts(1), parts(2)) else None } } object StudentApp extends App { val student = Student.separate("B123456, Bob, New Delhi") student match { case Some((number, name, addr)) => println(s"Student Information:::name=$name, number=$number and address=$addr") case None => println("Wrong data found") } }
  • 6. val students = List( "B123456,Ankit,New Delhi", "B123455,Anand,New Delhi", "B123454,Satendra,New Delhi") This is possible?? val Student(number, name, addr) = "B123456, Bob, New Delhi"
  • 7. Extractor (unapply) case class Student(number: String, name: String, address: String) val students = List( "B123456,Ankit,New Delhi", "B123455,Anand,New Delhi", "B123454,Satendra,New Delhi") val info: List[Student] = ???
  • 8. Extractor (unapply) def unapply(object: S): Option[T] object Student { def unapply(str: String): Option[(String, String, String)] = { val parts = str.split(",") if (parts.length == 3) Some(parts(0), parts(1), parts(2)) else None } }
  • 9. Extractor (unapply) object StudentApp extends App { val Student(number, name, addr) = "B123456, Bob, New Delhi" println(s"Student information=${(number, name, address)}") }
  • 10. Extractor (unapply) object StudentApp extends App { val students = List( "B123456,Ankit,New Delhi", "B123455,Anand,New Delhi", "B123454,Satendra,New Delhi") val result: List[Student] = students collect { case Student(number, name, address) => Student(number, name, address) } println(result) }
  • 11. Extractor (unapply) case class Student(number: String, name: String, address: String) object Student { def unapply(str: String): Option[(String, String, String)] = { val parts = str.split(",") if (parts.length == 3) Some(parts(0), parts(1), parts(2)) else None } } object Utility { def extractInformation(data: List[String]): List[Student] = { def extractInfo(extractedInfo: List[Student], result: List[String]): List[Student] = { result match { case Student(number, name, address) :: tail => extractInfo(extractedInfo :+ Student(number, name, address), tail) case Nil => extractedInfo case _ :: tail => extractInfo(extractedInfo, tail) } } extractInfo(List[Student](), data) } }
  • 12. Safe Extractor (unapply) object EMail { // The extraction method (mandatory) def unapply(str: String): Option[(String, String)] = { val parts = str split "@" if (parts.length == 2) Some(parts(0), parts(1)) else None } } object SafeExtractor extends App { val any: Any = "abdhehs@knoldus.com" any match { case EMail(user, domain) => println(s"Matched:::${(user, domain)}") case _ => println("Not Mathed") } }
  • 13. Extractor (unapply) object GivenNames { def unapply(name: String): Option[(String, String)] = { val names = name.trim.split(",") if (names.length >= 2) Some((names(1), names(0))) else None } } object ExtractNames extends App { def greetWithFirstName(name: String) = name match { case GivenNames(firstName, _) => "Good evening, " + firstName + "!" case _ => "Welcome! Please make sure to fill in your name!" } val information = "Kumar,Abdhesh,New Delhi" val result = greetWithFirstName(information) println(result) }
  • 14. object UserName { def unapplySeq(email: String): Option[Seq[String]] = { val parts = email split "," if (parts.nonEmpty) Some(parts) else None } } object UserNameApp extends App { val name = "Kumar,Abdhesh,New Delhi" name match { case UserName(lastName, firstName, _*) => println(s"First Name=$firstName and Last Name=$lastName") case _ => println("Not Matched") } val UserName(lastName, firstName, others @ _*) = name } Extract sequences (unapplySeq)
  • 15. object UserName { def unapplySeq(email: String): Option[Seq[String]] = { val parts = email split "," if (parts.nonEmpty) Some(parts) else None } } object UserNameApp extends App { val name = "Kumar,Abdhesh,New Delhi" name match { case UserName(lastName, firstName, others @ _*) => println(s"First Name=$firstName and Last Name=$lastName") case _ => println("Not Matched") } } Extract sequences (unapplySeq)..
  • 16. Wildcard operators  If you only care about the first variable you can use _* to reference the rest of the sequence that you don't care about  using @ _* we can get the rest of the sequence assigned to others
  • 17. Combining fixed and variable parameter extraction Sometimes, you have certain fixed values to be extracted that you know about at compile time, plus an additional optional sequence of values. def unapplySeq(object: S): Option[(T1, .., Tn-1, Seq[T])] *unapplySeq can also return an Option of a TupleN , where the last element of the tuple must be the
  • 18. Combining fixed and variable parameter extraction object Names { def unapplySeq(name: String): Option[(String, String, Seq[String])] = { val names = name.trim.split(" ") if (names.size < 2) None else Some((names.last, names.head, names.drop(1).dropRight(1))) } } object MixedExtractor { def greet(fullName: String) = fullName match { case Names(lastName, firstName, _*) => "Good morning, " + firstName + " " + lastName + "!" Case _ => "Welcome! Please make sure to fill in your name!" } }
  • 19. A Boolean Extractor object StudentBool { def unapply(student: String): Boolean = student.contains("Allahabad") } object BooleanExtractorApp extends App { val name = "B123456,Ankit,Allahabad" name match { case studentI @ StudentBool() => println(studentI) case _ => println("Not Found") } }
  • 20. A Boolean Extractor object StudentBool { def unapply(student: String): Boolean = student.contains("Allahabad") } object BooleanExtractorApp extends App { val students = List( "B123455,Anand,New Delhi", "B123454,Satendra,New Delhi", "B123456,Ankit,Allahabad") students collect { case std @ StudentBool() => std } }
  • 21. Instances of a class with unapply method class Splitter(sep: Char) { def unapply(v: String): Option[(String, String)] = (v indexOf sep) match { case x if (x > 0) => Some((v take x, v drop x + 1)) case _ => None } } object SimpleExtractor extends App { val SplitOnComma = new Splitter(',') "1,2" match { case SplitOnComma(one, two) => println(one, two) } //All extractors can also be used in assignments val SplitOnComma(one, two) = "1,2" }
  • 22. Every Regex object in Scala has an extractor object RegexExtractor extends App { val Decimal = new Regex("""(-)?(d+)(.d*)?""") val input = "for -1.0 to 99 by 3" for (s <- Decimal findAllIn input) println _ val dec = Decimal findFirstIn input val Decimal(sign, integerpart, decimalpart) = "-1.23" println((sign, integerpart, decimalpart)) val Decimal(signI, integerpartI, decimalpartI) = "32323" // Regex to split a date in the format Y/M/D. val regex = "(d+)/(d+)/(d+)".r val regex(year, month, day) = "2010/1/13" }
  • 23. Extractor Rules  unapply () method called extractor  unapply can’t be overloaded (because it always takes the the same argument).
  • 25. Where Implicits are Tried Implicits are used in three places in Scala ○ Conversions to an expected type ■ For objects passed in to a function that expects a different type
  • 26. Where Implicits are Tried.. ○ Conversions of the receiver of a selection ■ For when methods are called on an object that doesn't have those methods defined, but an implicit conversion does (e.g. -> method for maps)
  • 27. Where Implicits are Tried... ○ Implicit Parameters ■ Provide more information to a called method about what the caller wants ■ Especially useful with generic functions
  • 28. Rules for Implicit Marking Rule: Only definitions marked implicit are available The implicit keyword is used to mark which declarations the compiler may use as implicits. implicit def intToString(x: Int) = x.toString def dbl2Str(d: Double): String = d.toString // ignored
  • 29. Rules for Implicit Scope Rule: An inserted implicit conversion must be in scope as a single identifier, or be associated with the source or target type of the conversion.  The Scala compiler will only consider implicit conversions that are in scope  The compiler will also look for implicit definitions in the companion object of the source or expected target types of the conversion
  • 30. Rules for Implicit Non-Ambiguity Rule: An implicit conversion is only inserted if there is no other possible conversion to insert. One-at-a-time Rule: Only one implicit is tried. The compiler will never rewrite x + y to convert1(convert2(x)) + y.
  • 31. Rules for Implicit Explicits-First Rule: Whenever code type checks as it is written, no implicits are attempted
  • 32. Naming Conventions for Implicit  Can have arbitrary names  The compiler doesn't care  Naming should be chosen for two considerations:  Explicit usage of the conversion  Explicit importing into scope for the conversion
  • 33. Implicits Methods The idea is to be able to extend functionality of an existing class with new methods in a type safe manner.
  • 34. Implicits Methods class MyInteger(val i: Int) { def myNewMethod = println("hello from myNewMethod") def inc = new MyInteger(i + 1) } object MyIntegerConvertor { implicit def int2MyInt(i: Int) = new MyInteger(i) implicit def myInt2Int(mI: MyInteger) = mI.i } object ImplicitMethods extends App { import MyIntegerConvertor._ val result = 1.myNewMethod val inc = 2.inc def takesInt(i: Int) = println(i) takesInt(inc) takesInt(5.inc) }
  • 35. Implicits Parameters It is similar to default parameters, but it has a different mechanism for finding the “default” value. The implicit parameter is a parameter to method or constructor that is marked as implicit. This means if a parameter value is not mentioned then the compiler will search for an “implicit” value defined within a scope.
  • 36. Implicits Parameters object ImplicitParameters { def p(implicit i: Int) = print(i) def sayThings(implicit args: List[Any]) = args.foreach(println(_)) } object ImplicitParametersApp extends App { import ImplicitParameters._ implicit val nothingNiceToSay: List[Any] = Nil sayThings implicit val v = 2 }
  • 37. Implicits Parameters Matching implicit arguments  Implicits are totally typesafe, and are selected based on the static type of the arguments. Here are some examples to show how things work. def speakImplicitly(implicit greeting: String) = println(greeting) implicit val aUnit = () speakImplicitly //no implicit argument matching parameter type String was found.
  • 38. Implicits Parameters Implicit arguments of subtypes def sayThings(implicit args: List[Any]) = args.foreach(println(_)) implicit val nothingNiceToSay: List[Any] = Nil sayThings implicit val hello: List[String] = List("Hello world"); sayThings
  • 39. Implicits Parameters /** One important restriction is that there can only be a single implicit keyword per method. It must be at the start of a parameter list (which also makes all values of that parameter list be implicit). */ def pp(a: Int)(implicit i: Int) = println(a, i) //both i and b are implicit def pp(a: Int)(implicit i: Int, b: Long) = println(a, i, b) def pp(implicit i: Int, b: Long) = println(i, b) def pp(implicit i: Int, b: Long*) = println(i, b) def pp(b: Long*)(implicit i: Int) = println(i, b) /When you have a implicit keyword in the first of parameter list, all the parameters in this list are implicit!
  • 40. Implicit Classes  Must take exactly one parameter (Though can have a second, implicit parameter list)  Must be defined where a method could be defined (not at top level)  Generated method will have same name as the class, so can be imported together.
  • 41. Implicit Classes object Helpers { implicit class IntWithTimes(x: Int) { def times[A](f: => A): Unit = { def loop(current: Int): Unit = if (current > 0) { f loop(current - 1) } loop(x) } } } object ImpliciClasses { import Helpers._ 5 times println("HI") }
  • 42. Implicit Classes Implicit classes have the following restrictions: 1. They must be defined inside of another trait / class / object . 2.They may only take one non­implicit argument in their constructor. 3. There may not be any method, member or object in scope with the same name as the implicit class.
  • 43. Sort User Defined Objects case class Employee(id: Int, firstName: String, lastName: String) object Employee { implicit def orderingByName[A <: Employee]: Ordering[A] = Ordering.by(e => e.firstName) val orderingById: Ordering[Employee] = Ordering.by(e => e.id) }
  • 44. Sort User Defined Objects object ImplicitBox extends App { val employees = List( Employee(1, "A", "AA"), Employee(4, "D", "AA"), Employee(5, "E", "EE"), Employee(2, "B", "BB"), Employee(3, "C", "CC")) val sortByName = employees.sorted println(s"Sort Employee by name=${sortByName}") val sortById = employees.sorted(Employee.orderingById) println(s"Sort Employee by Id=${sortById}") }
  • 45. How can I chain/nest implicit conversions? Scala does not allow two such implicit conversions taking place, however, so one cannot got from A to C using an implicit A to B and another implicit B to C . Is there a way around this restriction? Scala has a restriction on automatic conversions to add a method, which is that it won’t apply more than one conversion in trying to find methods.
  • 46. How can I chain/nest implicit conversions? object T1 { implicit def toA(n: Int): A = new A(n) implicit def aToB(a: A): B = new B(a.n, a.n) implicit def bToC(b: B): C = new C(b.m, b.n, b.m + b.n) // won't work //println(5.total) //println(new A(5).total) // works println(new B(5, 5).total) println(new C(5, 5, 10).total) }
  • 47. How can I chain/nest implicit conversions? // def m[A <% B](m: A) is the same thing as // def m[A](m: A)(implicit ev: A => B) object T2 extends App { implicit def toA(n: Int): A = new A(n) implicit def aToB[A1 <% A](a: A1): B = new B(a.n, a.n) implicit def bToC[B1 <% B](b: B1): C = new C(b.m, b.n, b.m + b.n) // works println(5.total) println(new A(5).total) println(new B(5, 5).total) println(new C(5, 5, 10).total) }
  • 48. update method a(x) = y, the compiler interprets this to as a.update(x, y) class PhonebookExpend { private val numbers = scala.collection.mutable.Map[String, (Int, Int)]() def apply(name: String) = numbers(name) def update(name: String, number: (Int, Int)) = numbers(name) = number } object EchoUpdate extends App { val e = new Echo() e("hello", "hi") = "knoldus" //e("hello") = ("salut", "bonjour") val book2 = new PhonebookExpend() book2("jesse") = (123, 4567890) val (areaCode, local) = book2("jesse") }