Discuss the implementation of type bounds in Scala.
Instruction: Provide examples to explain upper type bounds and lower type bounds in Scala.
Updated
An upper bound A <: Pet requires A to be a subtype of Pet (including Pet itself), so code can use the operations declared by Pet. A lower bound B >: A requires B to be a supertype of A, which is useful when an operation widens a covariant container's element type.
This complete Scala 3 example demonstrates both:
trait Animal { def name: String }
trait Pet extends Animal { def play(): String }
final case class Dog(name: String) extends Pet {
def play(): String = s"$name fetches"
}
final case class Bird(name: String) extends Animal
final class PetCare[A <: Pet](pet: A) {
def exercise(): String = pet.play()
}
final case class Box[+A](values: List[A]) {
def prepend[B >: A](value: B): Box[B] = Box(value :: values)
}
@main def boundsExample(): Unit = {
assert(new PetCare(Dog("Rex")).exercise() == "Rex fetches")
val dogs: Box[Dog] = Box(List(Dog("Rex")))
val animals: Box[Animal] = dogs.prepend[Animal](Bird("Sky"))
assert(animals.values.map(_.name) == List("Sky", "Rex"))
assert(dogs.values.map(_.name) == List("Rex"))
}
PetCare[Bird] is rejected because Bird does not extend Pet. Prepending a bird creates a Box[Animal]; it does not somehow remain a Box[Dog] or change the original box. The actual declared inheritance relationship matters: merely naming a class Animal does not make it a supertype of Pet. Upper bounds, Lower bounds
A lower bound alone does not restrict additions to a business hierarchy: the compiler can sometimes choose a broader common supertype. Add an upper bound as well if the API must remain within a particular domain. Bounds express static subtype relationships; validation of values such as age or identifier format is a separate concern.