Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Covariance and contravariance. Say what?! (Agile Talks #22)

312 views

Published on

While merrily browsing the Internet and reading technical articles about programming, you may encounter the terms of "covariance" and "contravariance." These sound spooky enough to make you consider closing the tab and forgetting all about it, as if it were a bad dream. It doesn't have to be that way!

These two terms are actually abstract mathematical concepts that are used in probability theory, statistics, theoretical physics, category theory and (you guessed it!) computer science. Each aforementioned field has a certain definition regarding what covariance / contravariance is. Each definition may or may not have a degree of similarity to the other definitions in the other fields.

During this talk, we'll try to make sense of these things, together. We'll lightly touch upon what covariance and contravariance means in a couple of applied mathematical scenarios (Don't worry, we won't be talking about functors!). Then, we'll see how these concepts are used to describe subtyping relationships in programming languages such as Java and C#. There will be code examples, of course!

Published in: Technology
  • Be the first to comment

Covariance and contravariance. Say what?! (Agile Talks #22)

  1. 1. Covariance and Contravariance. Say what?!
  2. 2. Alin Pandichi
  3. 3. Alin Pandichi Open space Coding Dojo Bucharest Java User Group Global Day of Coderetreat
  4. 4. Alin Pandichi Open space Coding Dojo Bucharest Java User Group Global Day of Coderetreat Software developer @ Mozaic Labs Building eventriX
  5. 5. Covariance = the property of a function  of retaining its form when the variables  are linearly transformed.
  6. 6. Covariance = changing the input moves  the function in the same direction.
  7. 7. Contravariance = The basis and the vector  transform in an opposite way.
  8. 8. Contravariance = changing the input moves  the function in the opposite direction.
  9. 9. Covariance
  10. 10. Contravariance Covariance
  11. 11. 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.
  12. 12. 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
  13. 13. 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
  14. 14. 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.
  15. 15. ArrayList<Integer> ints = new ArrayList<Integer>(); ArrayList<? extends Number> nums = ints; Number   ←  Integer Number[]    ← 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”
  16. 16. ArrayList<Object> objs = new ArrayList<Object>(); ArrayList<? super Number> nums = objs; Object      ←  Number Object[]       ← 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”
  17. 17. Interesting properties of  covariance and contravariance: With covariance you can only  take values out. With contravariance you can  only put values in.
  18. 18. 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 error errs.add(new StackOverflowError("")); // compiler error
  19. 19. 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
  20. 20. 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);
  21. 21. In C#, covariant generic interfaces  are annotated with out: interface IMessageRecieved <out T> { T RecievedData(); } Covariance ­ take values out.
  22. 22. In C#, contravariant generic  interfaces are annotated with in: interface IMessageSend <in T> { void SendData(T data); } Contravariance – put values in.
  23. 23. 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>.
  24. 24. 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>.
  25. 25. class A { Object getSomething(){} } class B extends A { String getSomething() {} } Covariance because it returns a String   which extends Object (more derived)
  26. 26. 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)
  27. 27. Type systems that support  subtyping.
  28. 28. Programming language designers devising  typing rules for arrays, inheritance, and  generic datatypes
  29. 29. Programmers who use inheritance and  override methods.
  30. 30. Programmers who develop generic  interfaces, methods and code.
  31. 31. Subtyping  relation Data  access Overriding  methods Wildcard  generics Co variance Keep the  order Take  values  out More  derived  return  type extends Contra variance Reverse  the order Put  values in Less  derived  parameter  type super
  32. 32. Resources http://www.i­programmer.info/programming/theory/1632­covariance­and­c ontravariance­a­simple­guide.html https://dzone.com/articles/covariance­and­contravariance https://msdn.microsoft.com/en­us/library/dd799517(v=vs.110).aspx https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_s cience)#Covariant_arrays_in_Java_and_C.23 https://www.codeproject.com/articles/86419/variance­in­c­net­covariance­ and­contravarianc http://stackoverflow.com/questions/8481301/covariance­invariance­and­con travariance­explained­in­plain­english http://stackoverflow.com/questions/2501023/demonstrate­covariance­and ­contravariance­in­java#2501513
  33. 33. Image resources http://www.luchsinger­mathematics.ch/Var_Reduction.jpg https://i.kinja­img.com/gawker­media/image/upload/s­­7lQpqRh­­­/c_scal e,f_auto,fl_progressive,q_80,w_800/18ncmqm1vbv9vjpg.jpg http://classrealm.com/blog/wp­content/uploads/2012/03/WAildmath­300 x270.jpg http://www.i­programmer.info/images/stories/Core/Theory/covariance/ar rowscontraandco.jpg http://www.jonshawtrumpet.com/uploads/2/8/2/1/28211373/1670275_or ig.jpg https://www.memecreator.org/static/images/memes/3629822.jpg http://i2.kym­cdn.com/photos/images/newsfeed/000/085/283/philosorapt or.jpg https://cdn.meme.am/cache/instances/folder757/500x/65401757/katt­willi ams­shocked­let­me­rephrase­that­any­questions­i­can­answer.jpg https://pixabay.com/en/puzzle­game­solution­connection­226743/ https://pixabay.com/en/blur­cellphone­close­up­design­1867748/ http://www.moneyloveandlegacy.com/images/HandsGivingCoins.jpg http://hivhomekit.com/wp­content/uploads/2012/02/generic­stamp.png https://i.ytimg.com/vi/uCpirskzaO8/hqdefault.jpg

×