🔴 Scala Intermediate

What are type bounds in Scala generics?

Answer

Type bounds constrain which types can be used as generic type parameters. Upper bound (<:): def process[T <: Animal](t: T) — T must be Animal or a subtype. Similar to Java's <? extends Animal>. Lower bound (>:): def widen[T >: Dog](list: List[T]) — T must be Dog or a supertype. Used in covariant collections' methods. Context bound: def show[T: Show](t: T) — shorthand for implicit show: Show[T]. Requires a type class instance for T. View bound (deprecated): T <% Ordered[T] — T must be implicitly convertible to Ordered[T]. Multiple bounds: T <: Animal with Serializable. Type bounds enable writing generic code that works only with types that have specific capabilities, maintaining type safety while allowing flexibility.