Recall & Review
beginner
What is a type constraint with an upper bound in Kotlin?
It is a way to limit a generic type to be a subtype of a specific class or interface using the <T : UpperBound> syntax.Click to reveal answer
beginner
How do you declare a generic function in Kotlin that only accepts types extending Number?
Use fun <T : Number> functionName(param: T) { ... } to restrict T to Number or its subclasses.
Click to reveal answer
intermediate
Why use upper bounds in Kotlin generics?
To ensure the generic type has certain properties or functions, so you can safely call them inside the generic code.
Click to reveal answer
beginner
What happens if you try to use a type that does not meet the upper bound constraint?
The Kotlin compiler will show an error because the type does not satisfy the required subtype relationship.
Click to reveal answer
intermediate
Example: Explain this declaration: fun <T : Comparable<T>> sortList(list: List<T>)
This means T must implement Comparable of T, so the list elements can be compared and sorted safely.
Click to reveal answer
What does mean in Kotlin?
✗ Incorrect
The syntax restricts T to be Number or any subclass of Number.
Which of these types can be used for T in fun printLength(text: T)?
✗ Incorrect
String implements CharSequence, so it satisfies the upper bound constraint.
What error occurs if you pass a type not meeting the upper bound?
✗ Incorrect
Kotlin enforces type constraints at compile time, so it will not compile.
How do you specify multiple upper bounds in Kotlin?
✗ Incorrect
Use multiple constraints separated by commas with where clause: fun where T : Interface1, T : Interface2
What is the benefit of using upper bounds in generics?
✗ Incorrect
Upper bounds ensure the generic type has certain methods or properties, enabling safe calls.
Explain how to use upper bounds in Kotlin generics and why they are useful.
Think about limiting types to those that have certain features.
You got /4 concepts.
Describe a situation where you would use multiple upper bounds in Kotlin generics.
Consider when a type must have more than one trait.
You got /4 concepts.