Skip to content

Rewrote upper type bounds article #749

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 12, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 8 additions & 9 deletions tutorials/tour/_posts/2017-02-13-upper-type-bounds.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,18 +33,17 @@ class Lion extends Animal {
override def name: String = "Lion"
}

class Cage[P <: Pet](p: P) {
class PetContainer[P <: Pet](p: P) {
def pet: P = p
}

object Main extends App {
var dogCage = new Cage[Dog](new Dog)
var catCage = new Cage[Cat](new Cat)
/* Cannot put Lion in a cage as Lion is not a Pet. */
// var lionCage = new Cage[Lion](new Lion)
}
val dogContainer = new PetContainer[Dog](new Dog)
val catContainer = new PetContainer[Cat](new Cat)
// val lionContainer = new PetContainer[Lion](new Lion)
// ^this would not compile
```
The `class PetContainer` take a type parameter `P` which must be a subtype of `Pet`. `Dog` and `Cat` are subtypes of `Pet` so we can create a new `PetContainer[Dog]` and `PetContainer[Cat]`. However, if we tried to create a `PetContainer[Lion]`, we would get the following Error:

An instance of class `Cage` may contain an animal with upper bound `Pet`. An animal of type `Lion` is not a pet and therefore cannot be put into a cage.
`type arguments [Lion] do not conform to class PetContainer's type parameter bounds [P <: Pet]`

The usage of lower type bounds is discussed [here](lower-type-bounds.html).
This is because `Lion` is not a subtype of `Pet`.