SlideShare a Scribd company logo
1 of 23
SHAPELESSSHAPELESS
Generic programming for
Scala !
Generic programming for
Scala !
Deepti Bhardwaj
Trainee Software Consultant
Knoldus Software LLP
What is Shapeless?
● Type class
● Dependent type based generic programming
library for Scala
● Type class
● Dependent type based generic programming
library for Scala
Why Shapeless ?
● Shapeless is about programming with types.
● Doing things at compile-time that would more
commonly be done at runtime to ensure type-
safety and effectiveness.
Using Shapeless:
To include it in your SBT build you should add:
scalaVersion := "2.11.7"
libraryDependencies ++= Seq(
"com.chuusai" %% "shapeless" % "2.3.0")
1)Polymorphic function values
● Ordinary Scala function values are
monomorphic. Shapeless, however, provides
an encoding of polymorphic function values.
// Monomorphic method example
def findSize(s: String): Int = s.length
monomorphic("foo")
// Polymorphic method example
def findSize[T](l: List[T]): Int = l.length
findSize(List(1, 2, 3))
findSize(List("foo", "bar", "baz"))
Defining polymorphic function
values:
● The parametric polymorphism is moved to the method
inside the object.
● They are able to capture type-specific cases.
● Being polymorphic, they may be passed as arguments to
functions or methods and then applied to values of
different types within those functions.
HList Vs List
HLists are lists of objects of arbitrary types,
where the type information for each object is
kept. In fact, in Scala, we may do:
import shapeless._
val l = 10 :: "string" :: 1.0 :: Nil
but the type of l then would be List[Any], because
the common super type of the elements there
would be, in fact, only Any. A HList is declared
similarly to a List:
val hl = 10 :: "string" :: 1.0 :: HNil
except for the terminator HNil. But the type of hl is
actually Int :: String :: Double :: HNil.
HList vs Tuple
The benefit of using HLists instead of tuples is
that they can be used in all those situations
where a tuple would work just as well, but
without the 22-elements limit.
Also, shapeless allows standard Scala tuples
to be manipulated in exactly the same ways as
HLists.
2)Heterogenous lists
● It has a map operation, applying a
polymorphic function value across its
elements.
● It also has a flatMap operation.
● It has a set of fully polymorphic fold operations
which take a polymorphic binary function
value. The fold is sensitive to the static types
of all of the elements of the Hlist
3)Heterogenous maps
Shapeless provides a heterogenous map which
supports an arbitrary relation between the key
type and the corresponding value type,
class BiMapIS[K, V]
implicit val intToString = new BiMapIS[Int,String]
implicit val stringToInt = new BiMapIS[String, Int]
//this implies the map thus declared can have int as key and
String as value and vice - versa
monomorphic Scala map => monomorphic
function value
heterogenous shapeless map => polymorphic
function value
4)Coproduct
● a generalization of Scala's Either to an arbitrary number
of choices
● allows you to put together more than two types.
● Either with more than two possible types.
● Coproducts are mutually exclusive, only one of the
elements is going to be present at runtime.
5)Generic
● Simply put, a case class can be represented generically
as an HList of its component types — known as the
“generic representation”
● Converting a case class to/from its generic
representation is accomplished by using Generic!
trait Generic[T] {
type Repr
def to(t:T) :Repr
def from(r:Repr) :T }
case class Intern(name: String, email: String,id
:Int, address:String)
case class Employee(name: String, email:
String,id :Int, address:String)
we want to construct Employee from Intern
but want to do it automatically without passing
all parameters. Generic is used here !!
In this case, Employee and Intern are nearly
identical. What if the Employee had an extra
property or a less property?
The solution is provided by LabelledGeneric!
In this case, Employee and Intern are nearly
identical. What if the Employee had an extra
property or a less property?
The solution is provided by LabelledGeneric!
6)LabelledGeneric
● a case class can be represented generically
as a record of its component fields — known
as the “labelled generic representation”
References
https://github.com/milessabin/shapeless/wiki/Feature-https://github.com/milessabin/shapeless/wiki/Feature-
Demo
https://github.com/knoldus/shapeless-demo
Shapeless- Generic programming for Scala
Shapeless- Generic programming for Scala

More Related Content

What's hot

Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)
jeffz
 

What's hot (20)

TypeScript
TypeScriptTypeScript
TypeScript
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
String interpolation
String interpolationString interpolation
String interpolation
 
SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.
 
Introduction To C#
Introduction To C#Introduction To C#
Introduction To C#
 
All You Need to Know About Type Script
All You Need to Know About Type ScriptAll You Need to Know About Type Script
All You Need to Know About Type Script
 
Pattern Matching - at a glance
Pattern Matching - at a glancePattern Matching - at a glance
Pattern Matching - at a glance
 
1 kotlin vs. java: some java issues addressed in kotlin
1  kotlin vs. java: some java issues addressed in kotlin1  kotlin vs. java: some java issues addressed in kotlin
1 kotlin vs. java: some java issues addressed in kotlin
 
Few simple-type-tricks in scala
Few simple-type-tricks in scalaFew simple-type-tricks in scala
Few simple-type-tricks in scala
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 
An introduction to javascript
An introduction to javascriptAn introduction to javascript
An introduction to javascript
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
Start with swift
Start with swiftStart with swift
Start with swift
 
JavaScript Data Types
JavaScript Data TypesJavaScript Data Types
JavaScript Data Types
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
 
Java Tutorial Lab 5
Java Tutorial Lab 5Java Tutorial Lab 5
Java Tutorial Lab 5
 
String Interpolation in Scala
String Interpolation in ScalaString Interpolation in Scala
String Interpolation in Scala
 
Static and dynamic polymorphism
Static and dynamic polymorphismStatic and dynamic polymorphism
Static and dynamic polymorphism
 
Javascript analysis
Javascript analysisJavascript analysis
Javascript analysis
 

Viewers also liked

Viewers also liked (20)

BDD with Cucumber
BDD with CucumberBDD with Cucumber
BDD with Cucumber
 
Walk-through: Amazon ECS
Walk-through: Amazon ECSWalk-through: Amazon ECS
Walk-through: Amazon ECS
 
これがわかるとshapelessのコードも読めるかもしれない
これがわかるとshapelessのコードも読めるかもしれないこれがわかるとshapelessのコードも読めるかもしれない
これがわかるとshapelessのコードも読めるかもしれない
 
Introduction to Scala JS
Introduction to Scala JSIntroduction to Scala JS
Introduction to Scala JS
 
Drilling the Async Library
Drilling the Async LibraryDrilling the Async Library
Drilling the Async Library
 
Akka streams
Akka streamsAkka streams
Akka streams
 
Getting Started With AureliaJs
Getting Started With AureliaJsGetting Started With AureliaJs
Getting Started With AureliaJs
 
Mailchimp and Mandrill - The ‘Hominidae’ kingdom
Mailchimp and Mandrill - The ‘Hominidae’ kingdomMailchimp and Mandrill - The ‘Hominidae’ kingdom
Mailchimp and Mandrill - The ‘Hominidae’ kingdom
 
Realm Mobile Database - An Introduction
Realm Mobile Database - An IntroductionRealm Mobile Database - An Introduction
Realm Mobile Database - An Introduction
 
Kanban
KanbanKanban
Kanban
 
Introduction to Scala Macros
Introduction to Scala MacrosIntroduction to Scala Macros
Introduction to Scala Macros
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
 
An Introduction to Quill
An Introduction to QuillAn Introduction to Quill
An Introduction to Quill
 
Mandrill Templates
Mandrill TemplatesMandrill Templates
Mandrill Templates
 
Introduction to Knockout Js
Introduction to Knockout JsIntroduction to Knockout Js
Introduction to Knockout Js
 
Effective way to code in Scala
Effective way to code in ScalaEffective way to code in Scala
Effective way to code in Scala
 
Introduction to ScalaZ
Introduction to ScalaZIntroduction to ScalaZ
Introduction to ScalaZ
 
ANTLR4 and its testing
ANTLR4 and its testingANTLR4 and its testing
ANTLR4 and its testing
 
HTML5, CSS, JavaScript Style guide and coding conventions
HTML5, CSS, JavaScript Style guide and coding conventionsHTML5, CSS, JavaScript Style guide and coding conventions
HTML5, CSS, JavaScript Style guide and coding conventions
 
Functional programming in Javascript
Functional programming in JavascriptFunctional programming in Javascript
Functional programming in Javascript
 

Similar to Shapeless- Generic programming for Scala

JavaScript: Patterns, Part 2
JavaScript: Patterns, Part  2JavaScript: Patterns, Part  2
JavaScript: Patterns, Part 2
Chris Farrell
 
Introduction of C# BY Adarsh Singh
Introduction of C# BY Adarsh SinghIntroduction of C# BY Adarsh Singh
Introduction of C# BY Adarsh Singh
singhadarsh
 

Similar to Shapeless- Generic programming for Scala (20)

220 runtime environments
220 runtime environments220 runtime environments
220 runtime environments
 
What is the deal with Elixir?
What is the deal with Elixir?What is the deal with Elixir?
What is the deal with Elixir?
 
Complete Notes on Angular 2 and TypeScript
Complete Notes on Angular 2 and TypeScriptComplete Notes on Angular 2 and TypeScript
Complete Notes on Angular 2 and TypeScript
 
DEFUN 2008 - Real World Haskell
DEFUN 2008 - Real World HaskellDEFUN 2008 - Real World Haskell
DEFUN 2008 - Real World Haskell
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Erlang, an overview
Erlang, an overviewErlang, an overview
Erlang, an overview
 
Pig
PigPig
Pig
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
 
JavaScript: Patterns, Part 2
JavaScript: Patterns, Part  2JavaScript: Patterns, Part  2
JavaScript: Patterns, Part 2
 
Introduction of C# BY Adarsh Singh
Introduction of C# BY Adarsh SinghIntroduction of C# BY Adarsh Singh
Introduction of C# BY Adarsh Singh
 
Introduction to Python Part-1
Introduction to Python Part-1Introduction to Python Part-1
Introduction to Python Part-1
 
Intro to Scala
 Intro to Scala Intro to Scala
Intro to Scala
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
 
Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1
 
Pc module1
Pc module1Pc module1
Pc module1
 
About Functional Programming
About Functional ProgrammingAbout Functional Programming
About Functional Programming
 
scala.ppt
scala.pptscala.ppt
scala.ppt
 
ScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin OderskyScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin Odersky
 
OODP Unit 1 OOPs classes and objects
OODP Unit 1 OOPs classes and objectsOODP Unit 1 OOPs classes and objects
OODP Unit 1 OOPs classes and objects
 

More from Knoldus Inc.

More from Knoldus Inc. (20)

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
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptx
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 

Recently uploaded

%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 

Recently uploaded (20)

%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 

Shapeless- Generic programming for Scala

  • 1. SHAPELESSSHAPELESS Generic programming for Scala ! Generic programming for Scala ! Deepti Bhardwaj Trainee Software Consultant Knoldus Software LLP
  • 2. What is Shapeless? ● Type class ● Dependent type based generic programming library for Scala ● Type class ● Dependent type based generic programming library for Scala
  • 3. Why Shapeless ? ● Shapeless is about programming with types. ● Doing things at compile-time that would more commonly be done at runtime to ensure type- safety and effectiveness.
  • 4. Using Shapeless: To include it in your SBT build you should add: scalaVersion := "2.11.7" libraryDependencies ++= Seq( "com.chuusai" %% "shapeless" % "2.3.0")
  • 5. 1)Polymorphic function values ● Ordinary Scala function values are monomorphic. Shapeless, however, provides an encoding of polymorphic function values.
  • 6. // Monomorphic method example def findSize(s: String): Int = s.length monomorphic("foo") // Polymorphic method example def findSize[T](l: List[T]): Int = l.length findSize(List(1, 2, 3)) findSize(List("foo", "bar", "baz"))
  • 7. Defining polymorphic function values: ● The parametric polymorphism is moved to the method inside the object. ● They are able to capture type-specific cases. ● Being polymorphic, they may be passed as arguments to functions or methods and then applied to values of different types within those functions.
  • 8. HList Vs List HLists are lists of objects of arbitrary types, where the type information for each object is kept. In fact, in Scala, we may do: import shapeless._ val l = 10 :: "string" :: 1.0 :: Nil
  • 9. but the type of l then would be List[Any], because the common super type of the elements there would be, in fact, only Any. A HList is declared similarly to a List: val hl = 10 :: "string" :: 1.0 :: HNil except for the terminator HNil. But the type of hl is actually Int :: String :: Double :: HNil.
  • 10. HList vs Tuple The benefit of using HLists instead of tuples is that they can be used in all those situations where a tuple would work just as well, but without the 22-elements limit. Also, shapeless allows standard Scala tuples to be manipulated in exactly the same ways as HLists.
  • 11. 2)Heterogenous lists ● It has a map operation, applying a polymorphic function value across its elements. ● It also has a flatMap operation.
  • 12. ● It has a set of fully polymorphic fold operations which take a polymorphic binary function value. The fold is sensitive to the static types of all of the elements of the Hlist
  • 13. 3)Heterogenous maps Shapeless provides a heterogenous map which supports an arbitrary relation between the key type and the corresponding value type, class BiMapIS[K, V] implicit val intToString = new BiMapIS[Int,String] implicit val stringToInt = new BiMapIS[String, Int] //this implies the map thus declared can have int as key and String as value and vice - versa
  • 14. monomorphic Scala map => monomorphic function value heterogenous shapeless map => polymorphic function value
  • 15. 4)Coproduct ● a generalization of Scala's Either to an arbitrary number of choices ● allows you to put together more than two types. ● Either with more than two possible types. ● Coproducts are mutually exclusive, only one of the elements is going to be present at runtime.
  • 16. 5)Generic ● Simply put, a case class can be represented generically as an HList of its component types — known as the “generic representation” ● Converting a case class to/from its generic representation is accomplished by using Generic! trait Generic[T] { type Repr def to(t:T) :Repr def from(r:Repr) :T }
  • 17. case class Intern(name: String, email: String,id :Int, address:String) case class Employee(name: String, email: String,id :Int, address:String) we want to construct Employee from Intern but want to do it automatically without passing all parameters. Generic is used here !!
  • 18. In this case, Employee and Intern are nearly identical. What if the Employee had an extra property or a less property? The solution is provided by LabelledGeneric! In this case, Employee and Intern are nearly identical. What if the Employee had an extra property or a less property? The solution is provided by LabelledGeneric!
  • 19. 6)LabelledGeneric ● a case class can be represented generically as a record of its component fields — known as the “labelled generic representation”