Bird
Raised Fist0
Kotlinprogramming~20 mins

Generic constraints with where clause in Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Generic Constraints Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2:00remaining
Output of a generic function with where clause filtering
What is the output of the following Kotlin function when called with a list of integers [1, 2, 3, 4, 5]?
Kotlin
fun <T> filterAndDouble(items: List<T>): List<T> where T : Number, T : Comparable<T> {
    return items.filter { it.toDouble() > 2 }.map { (it.toDouble() * 2) as T }
}

val result = filterAndDouble(listOf(1, 2, 3, 4, 5))
println(result)
A[2, 4, 6, 8, 10]
BCompilation error due to casting
C[6, 8, 10]
D[3, 4, 5]
Attempts:
2 left
💡 Hint
Consider how casting from Double to T works in Kotlin generics.
📝 Syntax
intermediate
1:30remaining
Identify the correct syntax for generic constraints with where clause
Which of the following Kotlin function declarations correctly uses a where clause to constrain generic types?
Afun <T> process(item: T : CharSequence, T : Comparable<T>) { println(item.length) }
Bfun <T where T : CharSequence, T : Comparable<T>> process(item: T) { println(item.length) }
Cfun <T> process(item: T) where T : CharSequence, T : Comparable<T> { println(item.length) }
Dfun <T : CharSequence, T : Comparable<T>> process(item: T) { println(item.length) }
Attempts:
2 left
💡 Hint
Remember the correct placement of the where clause in Kotlin generic declarations.
❓ optimization
advanced
2:30remaining
Optimize generic function with multiple constraints and filtering
Given this Kotlin function, which option optimizes it to avoid unnecessary casting and improve type safety?
Kotlin
fun <T> sumIfGreaterThan(items: List<T>, threshold: T): Double where T : Number, T : Comparable<T> {
    return items.filter { it > threshold }.sumOf { it.toDouble() }
}
AReturn List<T> instead of Double to avoid sumOf
BChange return type to Double and keep code as is
CChange generic constraint to only Number and remove Comparable
DUse 'items.filter { it.toDouble() > threshold.toDouble() }.sumOf { it.toDouble() }' and keep constraints
Attempts:
2 left
💡 Hint
Think about how to compare generic numbers safely.
🔧 Debug
advanced
1:30remaining
Debug the compilation error in generic function with where clause
Why does the following Kotlin function cause a compilation error?
Kotlin
fun <T> printLength(item: T) where T : CharSequence, T : Comparable<T> {
    println(item.length)
}

printLength(123)
ABecause 123 is Int and does not satisfy CharSequence constraint
BBecause Comparable<T> constraint is missing
CBecause where clause syntax is incorrect
DBecause item.length is not accessible for generic T
Attempts:
2 left
💡 Hint
Check the type of argument passed and the constraints on T.
🧠 Conceptual
expert
2:00remaining
Understanding the purpose of where clause in Kotlin generics
What is the main purpose of using a where clause in Kotlin generic functions or classes?
ATo specify multiple constraints on a generic type when simple syntax is insufficient
BTo declare default values for generic types
CTo restrict generic types to only nullable types
DTo enable runtime type checking of generic parameters
Attempts:
2 left
💡 Hint
Think about why Kotlin allows where clauses beyond simple generic constraints.

Practice

(1/5)
1. What is the main purpose of using a where clause in Kotlin generic constraints?
easy
A. To override a generic type with a specific type
B. To specify multiple constraints on a generic type clearly
C. To create a new class without generics
D. To declare a generic function without any constraints

Solution

  1. Step 1: Understand generic constraints

    Generic constraints limit what types a generic can accept to ensure safety and functionality.
  2. Step 2: Role of where clause

    The where clause allows specifying multiple or complex constraints on a generic type clearly and separately from the main declaration.
  3. Final Answer:

    To specify multiple constraints on a generic type clearly -> Option B
  4. Quick Check:

    where clause = multiple constraints [OK]
Hint: Remember: where clause adds multiple constraints clearly [OK]
Common Mistakes:
  • Thinking where clause removes constraints
  • Confusing where clause with type declaration
  • Using where clause to override types
2. Which of the following is the correct syntax to add multiple constraints using a where clause in Kotlin?
easy
A. fun <T> example(item: T) where T : Comparable<T>, T : Serializable { }
B. fun <T> example(item: T : Comparable<T>, T : Serializable) { }
C. fun <T> example(item: T) : where T Comparable<T>, Serializable { }
D. fun <T> example(item: T) where T Comparable<T> and Serializable { }

Solution

  1. Step 1: Recall correct where clause syntax

    The where clause follows the generic parameter list and uses commas to separate constraints.
  2. Step 2: Validate each option

    fun <T> example(item: T) where T : Comparable<T>, T : Serializable { } correctly uses where T : Comparable<T>, T : Serializable. Others have syntax errors or misplaced keywords.
  3. Final Answer:

    fun <T> example(item: T) where T : Comparable<T>, T : Serializable { } -> Option A
  4. Quick Check:

    Correct where syntax = fun <T> example(item: T) where T : Comparable<T>, T : Serializable { } [OK]
Hint: Use commas to separate constraints in where clause [OK]
Common Mistakes:
  • Using colons inside parameter list instead of where clause
  • Adding 'and' instead of commas between constraints
  • Placing where clause after function body
3. Given the code below, what will be the output?
fun <T> printFirst(item: T) where T : List<String>, T : Comparable<T> {
    println(item[0])
}

fun main() {
    val list = listOf("apple", "banana")
    printFirst(list)
}
medium
A. Runtime error
B. banana
C. apple
D. Compilation error due to constraints

Solution

  1. Step 1: Analyze constraints on T

    The function requires T to be both List<String> and Comparable<T>.
  2. Step 2: Check if listOf<String> satisfies constraints

    List<String> does not implement Comparable<List<String>>, so it fails the constraint.
  3. Final Answer:

    Compilation error due to constraints -> Option D
  4. Quick Check:

    List<String> not Comparable = compilation error [OK]
Hint: Check if all constraints are met by the argument type [OK]
Common Mistakes:
  • Assuming List<String> is Comparable
  • Ignoring constraint errors at compile time
  • Expecting runtime error instead of compile error
4. Identify the error in the following Kotlin function using a where clause:
fun <T> compareItems(a: T, b: T) where T : Comparable {
    return a.compareTo(b) > 0
}
medium
A. Missing generic type parameter in Comparable constraint
B. Incorrect return type for the function
C. where clause should be after the function body
D. compareTo function does not exist

Solution

  1. Step 1: Check the constraint syntax

    The constraint T : Comparable is incomplete; Comparable requires a type parameter.
  2. Step 2: Correct constraint usage

    It should be T : Comparable<T> to specify T can be compared to itself.
  3. Final Answer:

    Missing generic type parameter in Comparable constraint -> Option A
  4. Quick Check:

    Comparable requires type parameter [OK]
Hint: Always specify type parameter for Comparable in constraints [OK]
Common Mistakes:
  • Omitting type parameter in Comparable
  • Placing where clause incorrectly
  • Assuming compareTo is undefined
5. You want to write a generic function that accepts any type T which must be both a Collection of Int and implement Iterable. Which is the correct way to declare the function with a where clause?
hard
A. fun <T> process(items: T) where T : Collection<Int>, Iterable<Int> { /*...*/ }
B. fun <T> process(items: T) where T : Collection, T : Iterable<Int> { /*...*/ }
C. fun <T> process(items: T) where T : Collection<Int>, T : Iterable<Int> { /*...*/ }
D. fun <T> process(items: T) where T : Collection<Int> and Iterable<Int> { /*...*/ }

Solution

  1. Step 1: Understand constraints needed

    The type T must be a Collection of Int and also implement Iterable of Int.
  2. Step 2: Correct where clause syntax

    Use commas to separate constraints and specify full generic types: T : Collection<Int>, T : Iterable<Int>.
  3. Final Answer:

    fun <T> process(items: T) where T : Collection<Int>, T : Iterable<Int> { /*...*/ } -> Option C
  4. Quick Check:

    Multiple constraints separated by commas = fun <T> process(items: T) where T : Collection<Int>, T : Iterable<Int> { /*...*/ } [OK]
Hint: Separate constraints with commas and repeat type parameter [OK]
Common Mistakes:
  • Omitting type parameter in Collection
  • Using 'and' instead of commas
  • Not repeating T for each constraint
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard