SlideShare a Scribd company logo
1 of 19
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

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 

Recently uploaded (20)

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 

Featured

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 ChatGPTExpeed 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 EngineeringsPixeldarts
 
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 HealthThinkNow
 
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.pdfmarketingartwork
 
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 2024Neil 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 2024Albert 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 InsightsKurio // 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 2024Search 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 summarySpeakerHub
 
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 IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit 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 managementMindGenius
 
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
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 

Featured (20)

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...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 

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