Skip to Content
Course content

30: Generics and Bounds

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've spent a lot of time reviewing code where the author was trying to write "flexible" logic, but they ended up fighting the compiler every step of the way. Usually, this happens when they try to handle a group of related classes without using generics properly. They think they're being general, but they're actually just erasing all the useful type information the compiler provides.

The Casting Trap

Imagine we're building a system to handle different types of financial instruments. We have a base trait called Asset, and specific implementations like Stock and Bond. You want a utility that finds the most valuable asset in a collection.

trait Asset { def value: Double }
case class Stock(symbol: String, value: Double) extends Asset
case class Bond(id: String, value: Double) extends Asset

object AssetUtils {
  def findMostValuable(assets: List[Asset]): Asset = {
    assets.maxBy(_.value)
  }
}

On the surface, this looks fine. It's simple and it works. But here is where it breaks in a real application. If you pass a List[Stock] into this method, the compiler sees a List[Asset]. When the method returns, you get back an Asset. If the rest of your business logic requires a Stock—say, to access the symbol field—you're forced to use a pattern match or a risky cast.

I call this "type erasure by choice." You've told the compiler to forget that these were stocks and just treat them as generic assets. You've traded type safety for a slightly shorter method signature, and now you're paying for it with boilerplate casts elsewhere in your codebase.

Preserving Type Identity with Upper Bounds

The better way is to use a generic type parameter with an upper bound. Instead of saying "this method takes a list of Assets," we say "this method takes a list of some type T, as long as T is a subtype of Asset."

object AssetUtils {
  def findMostValuable[T <: Asset](assets: List[T]): T = {
    assets.maxBy(_.value)
  }
}

The T <: Asset syntax is the magic here. It tells Scala: "I don't know exactly what T is yet, but I guarantee it will have everything an Asset has." Because the return type is also T, the type identity is preserved. If you pass in a List[Stock], you get back a Stock. No casting, no guesswork, and the compiler can prove the code is safe at compile time.

Broadening the Scope with Lower Bounds

Upper bounds are common, but lower bounds (T :> A) are the ones that usually trip people up because they feel counter-intuitive. While an upper bound restricts T to be "this or something smaller," a lower bound requires T to be "this or something larger."

You won't use these as often, but they are critical when you're writing "consumers" of data. Suppose you have a method that takes a collection of items and adds them to a generic "archive" container. You don't care if the items are Stock or Bond, but you need to be able to store them in a container that can hold at least any Asset.

def archiveAssets[T :> Asset](items: List[Asset], archive: scala.collection.mutable.ListBuffer[T]): Unit = {
  items.foreach(archive += item)
}

In this case, T :> Asset ensures that the archive is broad enough to hold an Asset. If you tried to pass a ListBuffer[Stock] as the archive, the compiler would stop you, because a buffer of stocks cannot safely hold a generic Asset (which might be a Bond). It's a way of ensuring the destination is "wide enough" for the data you're pushing into it.




📋 Practical Task

Implementation: Type-Safe Media Processor

You are building a media library. You have a base trait Media with a duration: Int property. There are two subtypes: Video (which has a resolution) and Audio (which has a bitrate).

Currently, the library has a findLongestMedia function that takes a List[Media] and returns a Media object. This is causing issues because the calling code has to manually cast the result to Video or Audio to access the resolution or bitrate.

Your Task:

  • Define the Media trait, and the Video and Audio case classes.
  • Rewrite the findLongestMedia function using generics and an upper bound so that if a List[Video] is passed in, a Video object is returned (and similarly for Audio).
  • Verify your implementation by creating a list of Video objects, passing them to the function, and accessing the resolution field on the result without using any explicit casting or pattern matching.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.