0
0
Kotlinprogramming~5 mins

Type constraints with upper bounds in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AT must be a supertype of Number
BT can be any type
CT must be a subtype of Number
DT must be exactly Number
Which of these types can be used for T in fun printLength(text: T)?
AString
BInt
CList
DBoolean
What error occurs if you pass a type not meeting the upper bound?
AWarning only
BRuntime exception
CNo error
DCompile-time error
How do you specify multiple upper bounds in Kotlin?
Afun <T : Interface1 & Interface2>
Bfun <T> where T : Interface1, T : Interface2
Cfun <T : Interface1, Interface2>
Dfun <T : Interface1; Interface2>
What is the benefit of using upper bounds in generics?
AAllows calling specific methods safely on generic types
BMakes code slower
CRemoves type safety
DAllows any type to be used
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.