Scala
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Scala
-
Section 4: Functional Scala
-
Section 5: Collections in Depth
-
Section 6: Type System
-
Section 7: Concurrency and Ecosystem
-
Section 8: Practical Projects
-
Section 9: Interview Practice
-
Section 10: Data Structures and Algorithms in Scala
-
Section 11: More Practice Exercises
-
Section 12: Advanced Functional Patterns
-
Section 13: More Ecosystem
-
Section 14: Scala Collections Library Deep Dive
-
Section 15: Scala Standard Library Deep Dive
-
Section 16: Akka Ecosystem Deep Dive
-
Section 17: Cats and Cats Effect Deep Dive
-
Section 18: Play Framework Deep Dive
-
Section 19: Apache Spark with Scala Deep Dive
-
Section 20: Scala Build Tools Deep Dive
-
Section 21: Scala 3 Specific Features
-
90: Union and Intersection Types
-
Section 22: Scala Testing Deep Dive
-
Section 23: Functional Domain Modeling
-
Section 24: More Data Structures and Algorithms in Scala
-
Section 25: Scala for Data Engineering
-
Section 26: More Practical Projects
-
Section 27: More Interview and Review
-
Section 28: ZIO Ecosystem Deep Dive
-
Section 29: Scala for Machine Learning
-
Section 30: Scala Microservices Architecture
-
Section 31: Scala Type System Deep Dive
-
Section 32: More Practice and Drills
-
Section 33: Scala Performance Deep Dive
-
Section 34: Scala Ecosystem Tooling
-
Section 35: Scala for Reactive Systems
-
Section 36: More Real-World Case Studies
-
Section 37: Scala for Financial Systems
-
Section 38: Scala GraphQL and gRPC
-
Section 39: More Final Projects
-
Section 40: More Interview and Final Review
-
Section 41: Scala for Streaming Data
-
Section 42: Scala Security Practices
-
Section 43: More Language Deep Dive
-
Section 44: Scala Command-Line Tools
-
Section 45: Scala Documentation and Style
-
Section 46: Scala Dependency Management
-
Section 47: More Practical Backend Patterns
-
Section 48: Scala for Event-Driven Architecture
-
Section 49: More Practice Drills Round 2
-
Section 50: Scala Compiler Deep Dive
-
Section 51: Scala for Web Frontends
-
Section 52: More Data Engineering Practice
-
Section 53: Scala Observability
-
Section 54: More Advanced Practice Projects
-
Section 55: Scala for Legacy Java Integration
-
Section 56: More Testing Practice
-
Section 57: Final Mastery Review
-
Section 58: Scala History and Ecosystem Context
-
Section 59: More Concurrency Patterns
-
Section 60: Scala for Configuration Management
-
Section 61: More Domain Modeling Practice
30: Generics and Bounds
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 aList[Asset]. When the method returns, you get back anAsset. If the rest of your business logic requires aStock—say, to access thesymbolfield—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 asTis a subtype ofAsset."object AssetUtils { def findMostValuable[T <: Asset](assets: List[T]): T = { assets.maxBy(_.value) } }The
T <: Assetsyntax is the magic here. It tells Scala: "I don't know exactly whatTis yet, but I guarantee it will have everything anAssethas." Because the return type is alsoT, the type identity is preserved. If you pass in aList[Stock], you get back aStock. 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 restrictsTto be "this or something smaller," a lower bound requiresTto 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
StockorBond, but you need to be able to store them in a container that can hold at least anyAsset.def archiveAssets[T :> Asset](items: List[Asset], archive: scala.collection.mutable.ListBuffer[T]): Unit = { items.foreach(archive += item) }In this case,
T :> Assetensures that thearchiveis broad enough to hold anAsset. If you tried to pass aListBuffer[Stock]as the archive, the compiler would stop you, because a buffer of stocks cannot safely hold a genericAsset(which might be aBond). 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
Mediatrait, and theVideoandAudiocase classes. - Rewrite the
findLongestMediafunction using generics and an upper bound so that if aList[Video]is passed in, aVideoobject is returned (and similarly forAudio). - Verify your implementation by creating a list of
Videoobjects, passing them to the function, and accessing theresolutionfield on the result without using any explicit casting or pattern matching.
There are no comments for now.