SlideShare a Scribd company logo
Demystifying Co, Contra, In
Kotlin
A Lightning Presentation (support slides 2023)
By João Esperancinha (2024/03/15)
Who am I?
● Software Engineer for 10+ years
● Java, Kotlin, Scala, Groovy, Clojure
● Studied at ISEL Lisboa in Computer Science and
Telecom Engineering
● Spring Professional 2020
● OCP11
● Kong Champion
Variances
The ability to establish
hierarchies between
complex types.
Example: is a list of
credit cards the same as
a list of cards and vice-
versa?
Sounds logic that a list
of credit cards is also a
list of cards, but is it?
Covariance
● Easy to understand
● Intuitive
● Restrictive
Covariance
abstract class DrinksService<in DRINK
: Drink, out BOX : Box> {
protected val database by lazy {
HashMap<UUID, Drink>() }
fun sendDrink(drink: DRINK) = run {
database[UUID.randomUUID()] = drink
}
abstract fun getBox(): BOX
}
open class Box
open class CardboardBox : Box()
open class PlasticBox : Box()
DrinkService is
covariant to Box!
Covariance
val coldDrinksBoxService: DrinksService<ColdDrink, Box> = object:
DrinksService<ColdDrink, FamilyBox>() {
override fun getBox(): FamilyBox {
TODO("Not yet implemented")
}
}
DrinkService is
covariant to Box!
Will this compile?
Yes! Because of covariance
DrinksService<ColdDrink, FamilyBox>
Is seen as a subclass of:
DrinksService<ColdDrink, Box>
👍
Covariance
val coldDrinksFamilyBoxService: DrinksService<ColdDrink, FamilyBox> =
object: DrinksService<ColdDrink, Box>() {
override fun getBox(): Box {
TODO("Not yet implemented")
}
}
DrinkService is
covariant to Box!
Will this compile?
No! Because of covariance
DrinksService<ColdDrink, Box>
Is NOT seen as a subclass of:
DrinksService<ColdDrink, FamilyBox>
👎
Contravariance
● Hard to understand
● Counter intuitive
● Restrictive
Covariance
abstract class DrinksService<in DRINK
: Drink, out BOX : Box> {
protected val database by lazy {
HashMap<UUID, Drink>() }
fun sendDrink(drink: DRINK) = run {
database[UUID.randomUUID()] = drink
}
abstract fun getBox(): BOX
}
open class Drink
open class WarmDrink : Drink()
open class ColdDrink : Drink()
DrinkService is
contravariant to
Drink!
Contravariance
val drinksFamilyBoxService: DrinksService<ColdDrink, FamilyBox> =
object : DrinksService<Drink, FamilyBox>() {
override fun getBox(): FamilyBox {
TODO("Not yet implemented")
}
}
DrinkService is
contravariant to Drink!
Will this compile?
Yes! Because of contravariance
DrinksService<ColdDrink, FamilyBox>
Is seen as a subclass of:
DrinksService<Drink, FamilyBox>
👍
Covariance
val coldDrinksFamilyBoxService: DrinksService<Drink, FamilyBox> =
object : DrinksService<ColdDrink, FamilyBox>() {
override fun getBox(): FamilyBox {
TODO("Not yet implemented")
}
}
DrinkService is
contravariant to Drink!
Will this compile?
No! Because of contravariance
DrinksService<Drink, FamilyBox>
Is not seen as a subclass of:
DrinksService<ColdDrink, FamilyBox>
👎
Contravariance can be very counterintuitive to
understand but essentially in common words, it means
that the combination with a certain complex type will still
result in a composed generic type in this case a
DrinksService<in DRINK : Drink, out BOX : Box>.
The idea is that the resulting composed type will have its
own hierarchy and that can move along or against the
original hierarchy of its individual contained types. And
so Drinks service is covariant to BOX, but contravariant
to DRINK. Therefore naturally if covariant, then the type
makes only sense to use as an output and thus the
modifier out. In the same if contravariant, then it only
make sense to use that generic type as input and thus in.
In Java
● Same implementation
● Same rules
● A bit more code
In Java - The Drinks Service
public class DrinksServiceJava<DRINK extends Drink, BOX extends Box> {
private final Map<UUID, DRINK> database = new HashMap<>();
public void sendDrink(DRINK drink) {
database.put(UUID.randomUUID(), drink);
}
@SuppressWarnings("unused")
public BOX getBox(Function<DRINK,BOX> drinks) {
return drinks.apply(database.remove(database.keySet().stream().findFirst().orElseThrow()));
}
}
In Java - Service initialization
DrinksServiceJava<? super WarmDrink, ? extends Box> drinksFamilyBoxService = new
DrinksServiceJava<Drink, FamilyBox>();
DrinkService is
contravariant to Drink!
DrinkService is
covariant to Box!
Different Language
Different Syntax
The same stuff
Resources
● https://kotlinlang.org
● https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.re
flect/-k-type-projection/
https://www.youtube.com/watch?v=D50Cluc2Vp4
Resources
● Source Repository
○ https://github.com/jesperancinha/asnsei-the-right-waf
● Location Directory:
○ https://github.com/jesperancinha/asnsei-the-right-waf/tree/main/demo-projects/drinks-manager
Use git clone from the command prompt to download the full code base:
> git clone https://github.com/jesperancinha/asnsei-the-right-waf.git
You’ll be prompted for a username and password which should be your github account.
> cd /demo-projects/drinks-manager
The easy way:
> make b
> make run
The manual way:
> gradle build
> ./gradlew run
Questions?
Thank you!

More Related Content

Recently uploaded

FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
UiPathCommunity
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..
UiPathCommunity
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 

Recently uploaded (20)

FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 

Featured

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
Marius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
Expeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
Pixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
ThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
marketingartwork
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
Skeleton Technologies
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
SpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Lily Ray
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
Rajiv Jayarajah, MAppComm, ACC
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
Christy Abraham Joy
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
Vit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
MindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
RachelPearson36
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Demystifying Co, Contra, In Kotlin modifier keywords.pptx

  • 1. Demystifying Co, Contra, In Kotlin A Lightning Presentation (support slides 2023) By João Esperancinha (2024/03/15)
  • 2. Who am I? ● Software Engineer for 10+ years ● Java, Kotlin, Scala, Groovy, Clojure ● Studied at ISEL Lisboa in Computer Science and Telecom Engineering ● Spring Professional 2020 ● OCP11 ● Kong Champion
  • 3. Variances The ability to establish hierarchies between complex types. Example: is a list of credit cards the same as a list of cards and vice- versa? Sounds logic that a list of credit cards is also a list of cards, but is it?
  • 4. Covariance ● Easy to understand ● Intuitive ● Restrictive
  • 5. Covariance abstract class DrinksService<in DRINK : Drink, out BOX : Box> { protected val database by lazy { HashMap<UUID, Drink>() } fun sendDrink(drink: DRINK) = run { database[UUID.randomUUID()] = drink } abstract fun getBox(): BOX } open class Box open class CardboardBox : Box() open class PlasticBox : Box() DrinkService is covariant to Box!
  • 6. Covariance val coldDrinksBoxService: DrinksService<ColdDrink, Box> = object: DrinksService<ColdDrink, FamilyBox>() { override fun getBox(): FamilyBox { TODO("Not yet implemented") } } DrinkService is covariant to Box! Will this compile? Yes! Because of covariance DrinksService<ColdDrink, FamilyBox> Is seen as a subclass of: DrinksService<ColdDrink, Box> 👍
  • 7. Covariance val coldDrinksFamilyBoxService: DrinksService<ColdDrink, FamilyBox> = object: DrinksService<ColdDrink, Box>() { override fun getBox(): Box { TODO("Not yet implemented") } } DrinkService is covariant to Box! Will this compile? No! Because of covariance DrinksService<ColdDrink, Box> Is NOT seen as a subclass of: DrinksService<ColdDrink, FamilyBox> 👎
  • 8. Contravariance ● Hard to understand ● Counter intuitive ● Restrictive
  • 9. Covariance abstract class DrinksService<in DRINK : Drink, out BOX : Box> { protected val database by lazy { HashMap<UUID, Drink>() } fun sendDrink(drink: DRINK) = run { database[UUID.randomUUID()] = drink } abstract fun getBox(): BOX } open class Drink open class WarmDrink : Drink() open class ColdDrink : Drink() DrinkService is contravariant to Drink!
  • 10. Contravariance val drinksFamilyBoxService: DrinksService<ColdDrink, FamilyBox> = object : DrinksService<Drink, FamilyBox>() { override fun getBox(): FamilyBox { TODO("Not yet implemented") } } DrinkService is contravariant to Drink! Will this compile? Yes! Because of contravariance DrinksService<ColdDrink, FamilyBox> Is seen as a subclass of: DrinksService<Drink, FamilyBox> 👍
  • 11. Covariance val coldDrinksFamilyBoxService: DrinksService<Drink, FamilyBox> = object : DrinksService<ColdDrink, FamilyBox>() { override fun getBox(): FamilyBox { TODO("Not yet implemented") } } DrinkService is contravariant to Drink! Will this compile? No! Because of contravariance DrinksService<Drink, FamilyBox> Is not seen as a subclass of: DrinksService<ColdDrink, FamilyBox> 👎
  • 12. Contravariance can be very counterintuitive to understand but essentially in common words, it means that the combination with a certain complex type will still result in a composed generic type in this case a DrinksService<in DRINK : Drink, out BOX : Box>. The idea is that the resulting composed type will have its own hierarchy and that can move along or against the original hierarchy of its individual contained types. And so Drinks service is covariant to BOX, but contravariant to DRINK. Therefore naturally if covariant, then the type makes only sense to use as an output and thus the modifier out. In the same if contravariant, then it only make sense to use that generic type as input and thus in.
  • 13. In Java ● Same implementation ● Same rules ● A bit more code
  • 14. In Java - The Drinks Service public class DrinksServiceJava<DRINK extends Drink, BOX extends Box> { private final Map<UUID, DRINK> database = new HashMap<>(); public void sendDrink(DRINK drink) { database.put(UUID.randomUUID(), drink); } @SuppressWarnings("unused") public BOX getBox(Function<DRINK,BOX> drinks) { return drinks.apply(database.remove(database.keySet().stream().findFirst().orElseThrow())); } }
  • 15. In Java - Service initialization DrinksServiceJava<? super WarmDrink, ? extends Box> drinksFamilyBoxService = new DrinksServiceJava<Drink, FamilyBox>(); DrinkService is contravariant to Drink! DrinkService is covariant to Box! Different Language Different Syntax The same stuff
  • 17. Resources ● Source Repository ○ https://github.com/jesperancinha/asnsei-the-right-waf ● Location Directory: ○ https://github.com/jesperancinha/asnsei-the-right-waf/tree/main/demo-projects/drinks-manager Use git clone from the command prompt to download the full code base: > git clone https://github.com/jesperancinha/asnsei-the-right-waf.git You’ll be prompted for a username and password which should be your github account. > cd /demo-projects/drinks-manager The easy way: > make b > make run The manual way: > gradle build > ./gradlew run