🔴 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.
More Scala Questions
View all →- Intermediate What is the type class pattern in Scala?
- Intermediate What is Akka and what is the actor model?
- Intermediate What is Apache Spark and how does Scala relate to it?
- Intermediate What is Scala's approach to concurrency with Futures and Promises?
- Intermediate What are Scala's monads and how do they work?