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

ODP
Knolx Session : Built-In Control Structures in Scala
ODP
Knolx Session: Introducing Extractors in Scala
PDF
Introducing Pattern Matching in Scala
PPTX
Java Tutorial Lab 3
PPTX
Java Tutorial Lab 5
PPT
Odersky week1 notes
PPTX
Lecture 9
PPTX
Java Tutorial Lab 7
Knolx Session : Built-In Control Structures in Scala
Knolx Session: Introducing Extractors in Scala
Introducing Pattern Matching in Scala
Java Tutorial Lab 3
Java Tutorial Lab 5
Odersky week1 notes
Lecture 9
Java Tutorial Lab 7

What's hot (20)

PPT
L11 array list
PPTX
Python Programming | JNTUK | UNIT 1 | Lecture 4
PPTX
Java Tutorial Lab 2
PPTX
Java Tutorial Lab 4
ODP
Java 1.5 - whats new and modern patterns (2007)
KEY
empty?, nil?, blank?, & present? (MOTM 2010.05)
PPTX
Java Tutorial Lab 6
PPTX
LISP: Data types in lisp
PDF
PPTX
LISP: Introduction to lisp
PPTX
Java tutorial part 4
PPTX
Types by Adform Research, Saulius Valatka
PPTX
Python dictionary
PPT
Scala in a nutshell by venkat
PDF
Python tuple
PPTX
Java 103 intro to java data structures
PPTX
Java Chapter 05 - Conditions & Loops: part 4
ODP
Functional programming with Scala
PPTX
Vector list nd sequence
L11 array list
Python Programming | JNTUK | UNIT 1 | Lecture 4
Java Tutorial Lab 2
Java Tutorial Lab 4
Java 1.5 - whats new and modern patterns (2007)
empty?, nil?, blank?, & present? (MOTM 2010.05)
Java Tutorial Lab 6
LISP: Data types in lisp
LISP: Introduction to lisp
Java tutorial part 4
Types by Adform Research, Saulius Valatka
Python dictionary
Scala in a nutshell by venkat
Python tuple
Java 103 intro to java data structures
Java Chapter 05 - Conditions & Loops: part 4
Functional programming with Scala
Vector list nd sequence
Ad

Viewers also liked (8)

PDF
Quick run in with Swagger
PPTX
COVARIANCE IN PROBABILITY
PPT
probability :- Covariance and correlation [email protected]
PPTX
Covariance
PDF
Introduction to measures of relationship: covariance, and Pearson r
PPTX
java thrift
DOC
Covariance and correlation
PPT
Analysis of covariance
Quick run in with Swagger
COVARIANCE IN PROBABILITY
probability :- Covariance and correlation [email protected]
Covariance
Introduction to measures of relationship: covariance, and Pearson r
java thrift
Covariance and correlation
Analysis of covariance
Ad

Similar to Covariance & Contravariance (20)

PDF
Covariance and contravariance. Say what?! (Agile Talks #22)
ODP
Type Parameterization
PDF
New c sharp4_features_part_ii
PDF
Understanding Scala variances
PDF
It Is Possible to Do Object-Oriented Programming in Java
PDF
Variance in scala
PDF
The Sincerest Form of Flattery
PDF
Dotnet programming concepts difference faqs- 2
PPT
Java Tutorial
PPTX
Whats New In C# 4 0 - NetPonto
PPTX
Learning core java
PDF
Kotlin Introduction with Android applications
PPTX
How We Stopped Worrying About Variance: Just Add +/- Until It Compiles
PDF
(eBook PDF) Data Structures and Other Objects Using Java 4th Edition
PPT
Generics lecture
PPTX
ICOM4015_CIIC4010 Exam Review #2
PPTX
L03 Software Design
PPTX
Collections Training
PDF
Demystifying Scala Type System
PDF
Kotlin: Challenges in JVM language design
Covariance and contravariance. Say what?! (Agile Talks #22)
Type Parameterization
New c sharp4_features_part_ii
Understanding Scala variances
It Is Possible to Do Object-Oriented Programming in Java
Variance in scala
The Sincerest Form of Flattery
Dotnet programming concepts difference faqs- 2
Java Tutorial
Whats New In C# 4 0 - NetPonto
Learning core java
Kotlin Introduction with Android applications
How We Stopped Worrying About Variance: Just Add +/- Until It Compiles
(eBook PDF) Data Structures and Other Objects Using Java 4th Edition
Generics lecture
ICOM4015_CIIC4010 Exam Review #2
L03 Software Design
Collections Training
Demystifying Scala Type System
Kotlin: Challenges in JVM language design

Recently uploaded (20)

PDF
EIS-Webinar-Regulated-Industries-2025-08.pdf
PDF
A symptom-driven medical diagnosis support model based on machine learning te...
PDF
Lung cancer patients survival prediction using outlier detection and optimize...
PDF
CXOs-Are-you-still-doing-manual-DevOps-in-the-age-of-AI.pdf
DOCX
Basics of Cloud Computing - Cloud Ecosystem
PDF
Dell Pro Micro: Speed customer interactions, patient processing, and learning...
PDF
Convolutional neural network based encoder-decoder for efficient real-time ob...
PDF
Introduction to MCP and A2A Protocols: Enabling Agent Communication
PDF
The-2025-Engineering-Revolution-AI-Quality-and-DevOps-Convergence.pdf
PDF
Transform-Your-Streaming-Platform-with-AI-Driven-Quality-Engineering.pdf
PDF
Transform-Your-Supply-Chain-with-AI-Driven-Quality-Engineering.pdf
PDF
Rapid Prototyping: A lecture on prototyping techniques for interface design
PDF
Transform-Quality-Engineering-with-AI-A-60-Day-Blueprint-for-Digital-Success.pdf
PDF
Electrocardiogram sequences data analytics and classification using unsupervi...
PDF
SaaS reusability assessment using machine learning techniques
PDF
giants, standing on the shoulders of - by Daniel Stenberg
PDF
Data Virtualization in Action: Scaling APIs and Apps with FME
PDF
Planning-an-Audit-A-How-To-Guide-Checklist-WP.pdf
PDF
Accessing-Finance-in-Jordan-MENA 2024 2025.pdf
PDF
AI.gov: A Trojan Horse in the Age of Artificial Intelligence
EIS-Webinar-Regulated-Industries-2025-08.pdf
A symptom-driven medical diagnosis support model based on machine learning te...
Lung cancer patients survival prediction using outlier detection and optimize...
CXOs-Are-you-still-doing-manual-DevOps-in-the-age-of-AI.pdf
Basics of Cloud Computing - Cloud Ecosystem
Dell Pro Micro: Speed customer interactions, patient processing, and learning...
Convolutional neural network based encoder-decoder for efficient real-time ob...
Introduction to MCP and A2A Protocols: Enabling Agent Communication
The-2025-Engineering-Revolution-AI-Quality-and-DevOps-Convergence.pdf
Transform-Your-Streaming-Platform-with-AI-Driven-Quality-Engineering.pdf
Transform-Your-Supply-Chain-with-AI-Driven-Quality-Engineering.pdf
Rapid Prototyping: A lecture on prototyping techniques for interface design
Transform-Quality-Engineering-with-AI-A-60-Day-Blueprint-for-Digital-Success.pdf
Electrocardiogram sequences data analytics and classification using unsupervi...
SaaS reusability assessment using machine learning techniques
giants, standing on the shoulders of - by Daniel Stenberg
Data Virtualization in Action: Scaling APIs and Apps with FME
Planning-an-Audit-A-How-To-Guide-Checklist-WP.pdf
Accessing-Finance-in-Jordan-MENA 2024 2025.pdf
AI.gov: A Trojan Horse in the Age of Artificial Intelligence

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)