Upload
alin-pandichi
View
250
Download
1
Embed Size (px)
Citation preview
Covariance andContravariance.
Say what?!
Alin Pandichi
Alin Pandichi
Open spaceCoding DojoBucharest Java User GroupGlobal Day of Coderetreat
Alin Pandichi
Open spaceCoding DojoBucharest Java User GroupGlobal Day of Coderetreat
Software developer @Mozaic LabsBuilding eventriX
Covariance = the property of a function of retaining its form when the variables
are linearly transformed.
Covariance = changing the input moves the function in the same direction.
Contravariance = The basis and the vector transform in an opposite way.
Contravariance = changing the input moves the function in the opposite direction.
Cov
aria
nce
Contravariance
Cov
aria
nce
Variance refers to how subtyping between complex types (lists, arrays) relates to
subtyping between their components (individual items).
Depending on variance, the subtyping relation may be either preserved, reversed, or ignored.
Integer is a subtype of Number Integer i = 1;Number n = i;
Number < Integer Number ← Integer
< means “is a subtype of”← means “can be assigned to”*read from right to the left
Integer[] is a subtype of Number[] Integer[] ints = {1, 2, 3};Number[] nums = ints;
Number[] < Integer[] Number[] ← Integer[]
< means “is a subtype of”← means “can be assigned to”*read from right to the left
Number ← Integer Number[] ← Integer[]
A B← means “B can be assigned to A”
Array types can be assigned in the same order.Arrays are covariant.
ArrayList<Integer> ints = new ArrayList<Integer>();ArrayList<? extends Number> nums = ints;
Number ← IntegerNumber[] ← Integer[]
<? extends Number> ← <Integer>
Can be assigned in the same order.This generic list is covariant.
A B← means “B can be assigned to A”
ArrayList<Object> objs = new ArrayList<Object>();ArrayList<? super Number> nums = objs;
Object ← NumberObject[] ← Number[]<Object> → <? super Number>
Can be assigned in the reverse order.This generic list is contravariant.
A B← means “B can be assigned to A”
Interesting properties of covariance and contravariance:
With covariance you can only take values out.
With contravariance you can only put values in.
With covariance you can only take values out.
ArrayList<? extends Error> errs = new ArrayList<StackOverflowError>();
Error e = errs.get(0);
errs.add(new Error("")); // compiler errorerrs.add(new StackOverflowError("")); // compiler error
With contravariance you can only put values in.
ArrayList<? super StackOverflowError> errs = new ArrayList<Error>();
errs.add(new StackOverflowError("w00t"));
Error e = errs.get(0); //compiler-error
StackOverflowError soe = errs.get(0); //compiler-error
public void copy(List<? extends Number> source,List<? super Number> destination) {
for(Number number : source) {destination.add(number);
}}
…
List<Integer> myInts = asList(1,2,3,4);List<Integer> myDoubles = asList(3.14, 6.28);List<Object> myObjs = new ArrayList<Object>();copy(myInts, myObjs);copy(myDoubles, myObjs);
In C#, covariant generic interfaces are annotated with out:
interface IMessageRecieved <out T>{
T RecievedData();}
Covariance take values out.
In C#, contravariant generic interfaces are annotated with in:
interface IMessageSend <in T>{
void SendData(T data);}
Contravariance – put values in.
Covariance
Enables you to use a more derived type than originally specified.
You can assign an instance of IEnumerable<Derived> to a variable of type IEnumerable<Base>.
Contravariance
Enables you to use a more generic (less derived) type than originally specified.
You can assign an instance of IEnumerable<Base> to a variable of type IEnumerable<Derived>.
class A { Object getSomething(){}}
class B extends A { String getSomething() {}}
Covariance because it returns a String which extends Object (more derived)
class A { void doSomething(String param){}}
class B extends A { void doSomething(Object param){}}
Contravariance because it takes an Object which is a super class of String (less derived)
Type systems that support subtyping.
Programming language designers devising typing rules for arrays, inheritance, and
generic datatypes
Programmers who use inheritance and override methods.
Programmers who develop generic interfaces, methods and code.
Subtyping relation
Data access
Overriding methods
Wildcard generics
Covariance
Keep the order
Take values
out
More derived return type
extends
Contravariance
Reverse the order
Put values in
Less derived
parameter type
super
Resources
http://www.iprogrammer.info/programming/theory/1632covarianceandcontravarianceasimpleguide.htmlhttps://dzone.com/articles/covarianceandcontravariancehttps://msdn.microsoft.com/enus/library/dd799517(v=vs.110).aspxhttps://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)#Covariant_arrays_in_Java_and_C.23https://www.codeproject.com/articles/86419/varianceincnetcovarianceandcontravarianchttp://stackoverflow.com/questions/8481301/covarianceinvarianceandcontravarianceexplainedinplainenglishhttp://stackoverflow.com/questions/2501023/demonstratecovarianceandcontravarianceinjava#2501513
Image resourceshttp://www.luchsingermathematics.ch/Var_Reduction.jpghttps://i.kinjaimg.com/gawkermedia/image/upload/s7lQpqRh/c_scale,f_auto,fl_progressive,q_80,w_800/18ncmqm1vbv9vjpg.jpghttp://classrealm.com/blog/wpcontent/uploads/2012/03/WAildmath300x270.jpghttp://www.iprogrammer.info/images/stories/Core/Theory/covariance/arrowscontraandco.jpghttp://www.jonshawtrumpet.com/uploads/2/8/2/1/28211373/1670275_orig.jpghttps://www.memecreator.org/static/images/memes/3629822.jpghttp://i2.kymcdn.com/photos/images/newsfeed/000/085/283/philosoraptor.jpghttps://cdn.meme.am/cache/instances/folder757/500x/65401757/kattwilliamsshockedletmerephrasethatanyquestionsicananswer.jpghttps://pixabay.com/en/puzzlegamesolutionconnection226743/https://pixabay.com/en/blurcellphonecloseupdesign1867748/http://www.moneyloveandlegacy.com/images/HandsGivingCoins.jpghttp://hivhomekit.com/wpcontent/uploads/2012/02/genericstamp.pnghttps://i.ytimg.com/vi/uCpirskzaO8/hqdefault.jpg