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

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
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
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
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
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
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
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
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
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 

Recently uploaded (20)

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
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
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 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
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
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
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
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
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

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)