Skip to content

Instantly share code, notes, and snippets.

@kknd22
Last active January 5, 2017 20:52
Show Gist options
  • Save kknd22/a383103c2278bf5ea859f54410fff1ef to your computer and use it in GitHub Desktop.
Save kknd22/a383103c2278bf5ea859f54410fff1ef to your computer and use it in GitHub Desktop.
scala +T -T convariance contravariance
http://blogs.atlassian.com/2013/01/covariance-and-contravariance-in-scala/
trait Function1[-T1, +R] {
def apply(t : T1) : R
...
}
This is single arg function in scala - T1 is basically input, R is output.
Any single arg function extends from this. And think through this rationally:
-T1 -> input needs to be less restrictive
+R -> output needs to be more restrictive
This allows the inheritance "is a" releation, any children "is a" Function1 ---> anything Function1 can do, mine can do.
Mine fucntion controls how T1 will be used - I might decide to not use anything. Return type R will be examed by others -
must at least as the originals
--------------------------------------------------------------------------------------------------------------------------------
http://blog.kamkor.me/Covariance-And-Contravariance-In-Scala/
SoftDrink
|
/ \
Cola TonicWater
class VendingMachine[+A](val currentItem: Option[A], items: List[A]) {
def this(items: List[A]) = this(None, items)
def addAll[B >: A](newItems: List[B]): VendingMachine[B] =
new VendingMachine(items ++ newItems)
}
// Covariant subtyping
A <: B
VendingMachine[A] <: VendingMachine[B]
val colasVM: VendingMachine[Cola] =
new VendingMachine(List(new Cola, new Cola))
val softDrinksVM: VendingMachine[SoftDrink] =
colasVM.addAll(List(new TonicWater))
// Contravariant subtyping
A <: B
GarbageCan[B] <: GarbageCan[A]
----------------------------------------------------------------------------------
Take a look scala List class http://www.scala-lang.org/api/2.7.1/scala/List.html
class List [+T]
+T also implies T is allow to grow to more super class direction.
e.g.
def union[B >: A](that: List[B]): List[B]
---------------------------------------------------------------------------------
Legal positions of covariant type parameter
In general, covariant type parameter can be used as immutable field type, method return type and also
as method argument type if the method argument type has a lower bound.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment