SlideShare a Scribd company logo
1 of 13
Download to read offline
Covariance & 
Contravariance 
Jihun Lee 
(c) Mesh Korea
Subtyping 
class A {} 
class B extends A {} 
void ABC(A a); 
! 
A inst = new B()  
ABC(new B()) 
Subtype of Array / 
Collection? 
class A {} 
class B extends A {} 
void ABC(A a); 
! 
A[] arr = new B[10] ? 
List<A> list = new List<B> ?
Subtype of Array / 
Collection? 
class A {} 
class B extends A {} 
void ABC(A a); 
A[] arr = new B[10]; 
B inst1 = new B(); 
A inst2 = new A(); 
arr[0] = inst1; 
arr[1] = inst2; 
Runtime Error!
Subtype of Array / 
Collection? 
class A {} 
class B extends A {} 
void ABC(A a); 
List<A> list = new List<B>(); 
B inst1 = new B(); 
A inst2 = new A(); 
list.add(inst1); 
list.add(inst2); 
Compile Error!
Mistakes of Java / C# 
• Early version of Java & C# did not include generics 
(parametric polymorphism) 
• What about Array.sort(Object[] A)? If SomeClass[] is 
not a subtype of Object[], we cannot use sort method! 
• Thus, they designed the language like that!!! 
• JVM should check runtime type all the time, and 
programmers should be careful about sub typing of 
arrays
Covariance & 
Contravariance 
• Co-variance(vary together!): preserves the 
ordering, which orders types from more specific 
to more generic. 
• Contra-variance(vary opposite): reverses the 
ordering! 
• In-variance(not vary): neither of them.
Covariance of Array 
• Let say Cat extends Animal 
• Not every Animal[] is not Cat[]. There may be Dog in 
Animal[]. 
• Cat[] cats = new Animal[]: X ( not contravariant ) 
• Not every Cat[] can not be treated as Animal[]. Maybe 
you want to put Dog into Animal[]. 
• Animal[] animals = new Cat[]: X ( should not be 
covariant)
Covariance of Array 
• Read-only data types can be covariant. 
• Write-only data types can be contravariant. 
• Mutable data types should be invariant.
Covariance of Array 
• Array is covariant in Java, C#. 
• Array is invariant in Scala.
Covariance of Function 
types 
• S1 → S2 ≤ T1 → T2 if T1 ≤ S1 and S2 ≤ T2 
• “->” is contravariant for the input type and is 
covariant in the output type.
Robustness principle 
“Be conservative in what you do, be liberal in 
what you accept from others” 
• Code that sends commands or data should 
conform completely to the specs. 
• Code that receives input should accept non-conformance 
input when meaning is clear.
Covariance of Generics 
• Declaration-site variance annotations ( C# ) 
interface IEnumerator<out T> 
{ 
T Current { get; } 
bool MoveNext(); 
} 
! 
• Use-site variance annotations ( Java ) 
<T extends Compaable<T>> T max(Collection<t> coll)

More Related Content

What's hot

L11 array list
L11 array listL11 array list
L11 array listteach4uin
 
Python Programming | JNTUK | UNIT 1 | Lecture 4
Python Programming | JNTUK | UNIT 1 | Lecture 4Python Programming | JNTUK | UNIT 1 | Lecture 4
Python Programming | JNTUK | UNIT 1 | Lecture 4FabMinds
 
Java Tutorial Lab 2
Java Tutorial Lab 2Java Tutorial Lab 2
Java Tutorial Lab 2Berk Soysal
 
Java Tutorial Lab 4
Java Tutorial Lab 4Java Tutorial Lab 4
Java Tutorial Lab 4Berk Soysal
 
Java 1.5 - whats new and modern patterns (2007)
Java 1.5 - whats new and modern patterns (2007)Java 1.5 - whats new and modern patterns (2007)
Java 1.5 - whats new and modern patterns (2007)Peter Antman
 
empty?, nil?, blank?, & present? (MOTM 2010.05)
empty?, nil?, blank?, & present? (MOTM 2010.05)empty?, nil?, blank?, & present? (MOTM 2010.05)
empty?, nil?, blank?, & present? (MOTM 2010.05)Kevin Munc
 
Java Tutorial Lab 6
Java Tutorial Lab 6Java Tutorial Lab 6
Java Tutorial Lab 6Berk Soysal
 
Types by Adform Research, Saulius Valatka
Types by Adform Research, Saulius ValatkaTypes by Adform Research, Saulius Valatka
Types by Adform Research, Saulius ValatkaVasil Remeniuk
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structuresagorolabs
 
Java Chapter 05 - Conditions & Loops: part 4
Java Chapter 05 - Conditions & Loops: part 4Java Chapter 05 - Conditions & Loops: part 4
Java Chapter 05 - Conditions & Loops: part 4DanWooster1
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with ScalaNeelkanth Sachdeva
 

What's hot (20)

L11 array list
L11 array listL11 array list
L11 array list
 
Python Programming | JNTUK | UNIT 1 | Lecture 4
Python Programming | JNTUK | UNIT 1 | Lecture 4Python Programming | JNTUK | UNIT 1 | Lecture 4
Python Programming | JNTUK | UNIT 1 | Lecture 4
 
Java Tutorial Lab 2
Java Tutorial Lab 2Java Tutorial Lab 2
Java Tutorial Lab 2
 
Java Tutorial Lab 4
Java Tutorial Lab 4Java Tutorial Lab 4
Java Tutorial Lab 4
 
Java 1.5 - whats new and modern patterns (2007)
Java 1.5 - whats new and modern patterns (2007)Java 1.5 - whats new and modern patterns (2007)
Java 1.5 - whats new and modern patterns (2007)
 
empty?, nil?, blank?, & present? (MOTM 2010.05)
empty?, nil?, blank?, & present? (MOTM 2010.05)empty?, nil?, blank?, & present? (MOTM 2010.05)
empty?, nil?, blank?, & present? (MOTM 2010.05)
 
Java Tutorial Lab 6
Java Tutorial Lab 6Java Tutorial Lab 6
Java Tutorial Lab 6
 
LISP: Data types in lisp
LISP: Data types in lispLISP: Data types in lisp
LISP: Data types in lisp
 
Swift
SwiftSwift
Swift
 
LISP: Introduction to lisp
LISP: Introduction to lispLISP: Introduction to lisp
LISP: Introduction to lisp
 
Java tutorial part 4
Java tutorial part 4Java tutorial part 4
Java tutorial part 4
 
Types by Adform Research, Saulius Valatka
Types by Adform Research, Saulius ValatkaTypes by Adform Research, Saulius Valatka
Types by Adform Research, Saulius Valatka
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
Python tuple
Python   tuplePython   tuple
Python tuple
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
 
Java Chapter 05 - Conditions & Loops: part 4
Java Chapter 05 - Conditions & Loops: part 4Java Chapter 05 - Conditions & Loops: part 4
Java Chapter 05 - Conditions & Loops: part 4
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
 
Vector list nd sequence
Vector list nd sequenceVector list nd sequence
Vector list nd sequence
 
Intro++ to C#
Intro++ to C#Intro++ to C#
Intro++ to C#
 

Viewers also liked

Quick run in with Swagger
Quick run in with SwaggerQuick run in with Swagger
Quick run in with SwaggerMesh Korea
 
probability :- Covariance and correlation Faisalkhan2081@yahoo.com
probability :- Covariance and correlation Faisalkhan2081@yahoo.comprobability :- Covariance and correlation Faisalkhan2081@yahoo.com
probability :- Covariance and correlation Faisalkhan2081@yahoo.comFaisal Khan
 
Introduction to measures of relationship: covariance, and Pearson r
Introduction to measures of relationship: covariance, and Pearson rIntroduction to measures of relationship: covariance, and Pearson r
Introduction to measures of relationship: covariance, and Pearson rIvan Jacob Pesigan
 
Covariance and correlation
Covariance and correlationCovariance and correlation
Covariance and correlationRashid Hussain
 
Analysis of covariance
Analysis of covarianceAnalysis of covariance
Analysis of covariancemikko656
 

Viewers also liked (8)

Quick run in with Swagger
Quick run in with SwaggerQuick run in with Swagger
Quick run in with Swagger
 
COVARIANCE IN PROBABILITY
COVARIANCE IN PROBABILITYCOVARIANCE IN PROBABILITY
COVARIANCE IN PROBABILITY
 
probability :- Covariance and correlation Faisalkhan2081@yahoo.com
probability :- Covariance and correlation Faisalkhan2081@yahoo.comprobability :- Covariance and correlation Faisalkhan2081@yahoo.com
probability :- Covariance and correlation Faisalkhan2081@yahoo.com
 
Covariance
CovarianceCovariance
Covariance
 
Introduction to measures of relationship: covariance, and Pearson r
Introduction to measures of relationship: covariance, and Pearson rIntroduction to measures of relationship: covariance, and Pearson r
Introduction to measures of relationship: covariance, and Pearson r
 
java thrift
java thriftjava thrift
java thrift
 
Covariance and correlation
Covariance and correlationCovariance and correlation
Covariance and correlation
 
Analysis of covariance
Analysis of covarianceAnalysis of covariance
Analysis of covariance
 

Similar to Covariance & Contravariance

Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from javaIndicThreads
 
Type Parameterization
Type ParameterizationType Parameterization
Type ParameterizationKnoldus Inc.
 
Scala-对Java的修正和超越
Scala-对Java的修正和超越Scala-对Java的修正和超越
Scala-对Java的修正和超越Caoyuan Deng
 
CallSharp: Automatic Input/Output Matching in .NET
CallSharp: Automatic Input/Output Matching in .NETCallSharp: Automatic Input/Output Matching in .NET
CallSharp: Automatic Input/Output Matching in .NETDmitri Nesteruk
 
(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
 
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 kotlinSergey Bandysik
 
Equality For All!
Equality For All!Equality For All!
Equality For All!bvenners
 
Java10 Collections and Information
Java10 Collections and InformationJava10 Collections and Information
Java10 Collections and InformationSoftNutx
 
Power of functions in a typed world
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed worldDebasish Ghosh
 
Real World Haskell: Lecture 4
Real World Haskell: Lecture 4Real World Haskell: Lecture 4
Real World Haskell: Lecture 4Bryan O'Sullivan
 
Text processing
Text processingText processing
Text processingIcancode
 
OCA Java SE 8 Exam Chapter 3 Core Java APIs
OCA Java SE 8 Exam Chapter 3 Core Java APIsOCA Java SE 8 Exam Chapter 3 Core Java APIs
OCA Java SE 8 Exam Chapter 3 Core Java APIsİbrahim Kürce
 
Javase5generics
Javase5genericsJavase5generics
Javase5genericsimypraz
 
Ruby data types and objects
Ruby   data types and objectsRuby   data types and objects
Ruby data types and objectsHarkamal Singh
 

Similar to Covariance & Contravariance (20)

Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
 
Type Parameterization
Type ParameterizationType Parameterization
Type Parameterization
 
Scala-对Java的修正和超越
Scala-对Java的修正和超越Scala-对Java的修正和超越
Scala-对Java的修正和超越
 
CallSharp: Automatic Input/Output Matching in .NET
CallSharp: Automatic Input/Output Matching in .NETCallSharp: Automatic Input/Output Matching in .NET
CallSharp: Automatic Input/Output Matching in .NET
 
(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?
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
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
 
arrays.pptx
arrays.pptxarrays.pptx
arrays.pptx
 
Equality For All!
Equality For All!Equality For All!
Equality For All!
 
Java10 Collections and Information
Java10 Collections and InformationJava10 Collections and Information
Java10 Collections and Information
 
Power of functions in a typed world
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed world
 
ACP-arrays.pptx
ACP-arrays.pptxACP-arrays.pptx
ACP-arrays.pptx
 
Real World Haskell: Lecture 4
Real World Haskell: Lecture 4Real World Haskell: Lecture 4
Real World Haskell: Lecture 4
 
Real generics
Real genericsReal generics
Real generics
 
Text processing
Text processingText processing
Text processing
 
ch11.ppt
ch11.pptch11.ppt
ch11.ppt
 
OCA Java SE 8 Exam Chapter 3 Core Java APIs
OCA Java SE 8 Exam Chapter 3 Core Java APIsOCA Java SE 8 Exam Chapter 3 Core Java APIs
OCA Java SE 8 Exam Chapter 3 Core Java APIs
 
Javase5generics
Javase5genericsJavase5generics
Javase5generics
 
Arrays
ArraysArrays
Arrays
 
Ruby data types and objects
Ruby   data types and objectsRuby   data types and objects
Ruby data types and objects
 

Recently uploaded

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 

Recently uploaded (20)

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 

Covariance & Contravariance

  • 1. Covariance & Contravariance Jihun Lee (c) Mesh Korea
  • 2. Subtyping class A {} class B extends A {} void ABC(A a); ! A inst = new B()  ABC(new B()) 
  • 3. Subtype of Array / Collection? class A {} class B extends A {} void ABC(A a); ! A[] arr = new B[10] ? List<A> list = new List<B> ?
  • 4. Subtype of Array / Collection? class A {} class B extends A {} void ABC(A a); A[] arr = new B[10]; B inst1 = new B(); A inst2 = new A(); arr[0] = inst1; arr[1] = inst2; Runtime Error!
  • 5. Subtype of Array / Collection? class A {} class B extends A {} void ABC(A a); List<A> list = new List<B>(); B inst1 = new B(); A inst2 = new A(); list.add(inst1); list.add(inst2); Compile Error!
  • 6. Mistakes of Java / C# • Early version of Java & C# did not include generics (parametric polymorphism) • What about Array.sort(Object[] A)? If SomeClass[] is not a subtype of Object[], we cannot use sort method! • Thus, they designed the language like that!!! • JVM should check runtime type all the time, and programmers should be careful about sub typing of arrays
  • 7. Covariance & Contravariance • Co-variance(vary together!): preserves the ordering, which orders types from more specific to more generic. • Contra-variance(vary opposite): reverses the ordering! • In-variance(not vary): neither of them.
  • 8. Covariance of Array • Let say Cat extends Animal • Not every Animal[] is not Cat[]. There may be Dog in Animal[]. • Cat[] cats = new Animal[]: X ( not contravariant ) • Not every Cat[] can not be treated as Animal[]. Maybe you want to put Dog into Animal[]. • Animal[] animals = new Cat[]: X ( should not be covariant)
  • 9. Covariance of Array • Read-only data types can be covariant. • Write-only data types can be contravariant. • Mutable data types should be invariant.
  • 10. Covariance of Array • Array is covariant in Java, C#. • Array is invariant in Scala.
  • 11. Covariance of Function types • S1 → S2 ≤ T1 → T2 if T1 ≤ S1 and S2 ≤ T2 • “->” is contravariant for the input type and is covariant in the output type.
  • 12. Robustness principle “Be conservative in what you do, be liberal in what you accept from others” • Code that sends commands or data should conform completely to the specs. • Code that receives input should accept non-conformance input when meaning is clear.
  • 13. Covariance of Generics • Declaration-site variance annotations ( C# ) interface IEnumerator<out T> { T Current { get; } bool MoveNext(); } ! • Use-site variance annotations ( Java ) <T extends Compaable<T>> T max(Collection<t> coll)