Download - Scala’s implicits
Scala’s Implicits
Pablo Francisco Pérez Hidalgo (@pfcoperez)github.com/pfcoperez
Scala’s Implicits Implicit Values
Pablo Francisco Pérez Hidalgo (@pfcoperez)github.com/pfcoperez
Scala 101
Programming 101: Formal vs Actual parameters
Scala 101: Lists of parameters
Scala 101: Methods are not functions
… but they are kind of cousins.
Know your implicit things
The compiler’s toy box: Implicit parameters Just for methods
The compiler’s toy box: Implicit parameters Just for methods
The compiler’s toy box: Implicit parameters Just for methods
The compiler’s toy box: Implicit conversions
Conversion:Domain = R
-10.0, 1.3, 9.2, ….
Conversion, I am your SOURCE TYPE
And, I am your TARGET TYPE
Implicit conversions: A silly example
Facts
Actual implicit parameters are values.
Formal implicit parameters are all those in the implicit parameter list.
Only methods can have - a single - implicit parameter list.
Functions are values.Guinea Pigs are pets, not food.
Implicit conversions are specially tagged functions, that is values.
Methods are not functions but can be assigned to function values thus becoming functions so they can become implicit conversions.
Know your implicit context
The implicit context
Compound Noun (singular)The place from where the magic unicorns come...
The implicit contexterror: ambiguous implicit values: both value c of type => C and value d of type => C
WHY?! WHAT?!Where did that implicit value came from???!!!
I DONT KNOW MORTY! BUT… RUN! RUN! RUN!
The implicit context is, once tamed, is... MOSTLY HARMLESSImplicit Context (n)The implicit context at a given point of your source code is the set of implicit values available for the compiler to perform type conversions or complete function calls when that point of code is providing an unexpected type object or missing some parameter in a function call.
That is… a mere backpack full of values for the compiler to use.
Identifying the limits of your implicit context
Identifying the limits of your implicit context: Scope
Identifying the limits of your implicit context: Implicit parameters
Identifying the limits of your implicit context: Target & goal companion objects
Conversion Source Type Target Type
A B
B A
B A
Patterns, let’s take it easy
Representing context
Representing context
Basic exercise
Fighting type erasure:The compiler & implicit values to the rescue
Adventure time
Problem
Old-school solution
Traditional OOP
Solution
Type classes to therescue
Maintainable += Animal
Maintainable += Equipment
Type classes to therescue
That wasn’t just a hack...
A magnetic way of solving the same problem...
A magnetic way of solving the same problem...