Skip to content

Instantly share code, notes, and snippets.

@stuntgoat
Last active August 29, 2015 14:06
Show Gist options
  • Save stuntgoat/e02dff598c772506de7c to your computer and use it in GitHub Desktop.
Save stuntgoat/e02dff598c772506de7c to your computer and use it in GitHub Desktop.
/**
Here's an example of failing to return the correct type
*/
object CovarianceExampleFailFirst {
/**
Covariance example (does not compile)
def mixFoods[T >: Watermelon](food: T): List[T] = {
This method definition states that within the context of
the mixFoodsFail method, there is a type T that is either
a Watermelon or a subclass of Watermelon.
Given what we know about type T, this method will accept an argument
of type T and return a list of type T.
Unfortuanately, this code will not compile since we are
attempting to return a GardenItem within the list of what
can only contain type T.
*/
def mixFoods[T >: Watermelon](food: T): List[T] = {
food match {
case x: FruitSalad => {
/**
This will not compile because GardenItem is not a
subclass of Watermelon; it's a superclass of Watermelon.
*/
List(new GardenItem, food) // Fails!
}
case _ => List()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment