Skip to content

Instantly share code, notes, and snippets.

@stuntgoat
Created September 19, 2014 06:55
Show Gist options
  • Save stuntgoat/ae14264e0017c50296c4 to your computer and use it in GitHub Desktop.
Save stuntgoat/ae14264e0017c50296c4 to your computer and use it in GitHub Desktop.
/**
Here is an object that has a method mixFoods which will accept
a subclass of a GardenItem and return a list of either
GardenItems or subclasses of GardenItems.
*/
object CovarianceExample {
/**
Covariance example (compiles)
def mixFoods[T >: GardenItem](food: T): List[T] = {
This method definition states that within the context of the
mixFoods method, there is a type T that is a superclass of a GardenItem.
We then go on to say that this method accepts an argument which
is of type T, a subclass of GardenItem and it returns a List of
either GardenItems or subclasses of GardenItems.
*/
def mixFoods[T >: GardenItem](food: T): List[T] = {
food match {
case x: FruitSalad => {
/**
Watermelon is a subclass of GardenItem so this is valid
to the compiler.
*/
List(new Watermelon, food)
}
case x: Cucumber => {
/**
Cocktail is a subclass of Cucumber, which is a subclass of
GardenItem so this is also valid to the compiler.
*/
List(food, new Cocktail)
}
case _ => List()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment