Bird
Raised Fist0
Kotlinprogramming~20 mins

Generic class declaration in Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Generic Class Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of a simple generic class usage
What is the output of this Kotlin code that uses a generic class?
Kotlin
class Box<T>(val value: T) {
    fun getValue(): T = value
}

fun main() {
    val box = Box(123)
    println(box.getValue())
}
A123
BBox@<hashcode>
CCompilation error
Dnull
Attempts:
2 left
💡 Hint
Look at how the generic class stores and returns the value.
❓ Predict Output
intermediate
2:00remaining
Output with generic class and type inference
What will this Kotlin program print when using a generic class with type inference?
Kotlin
class Container<T>(val item: T) {
    fun describe(): String = "Item is: $item"
}

fun main() {
    val c = Container("Hello")
    println(c.describe())
}
ACompilation error due to missing type
BItem is: Container@<hashcode>
CItem is: Hello
DItem is: null
Attempts:
2 left
💡 Hint
The generic type is inferred from the constructor argument.
🧠 Conceptual
advanced
2:00remaining
Understanding generic type constraints
Which option correctly declares a generic class in Kotlin that only accepts types which implement the Comparable interface?
Aclass Sortable<T>(val item: T) where T : Comparable<T>
Bclass Sortable<T>(val item: T) where T : Comparable
Cclass Sortable<T : Comparable>(val item: T)
Dclass Sortable<T : Comparable<T>>(val item: T)
Attempts:
2 left
💡 Hint
Look for the correct syntax for generic constraints in Kotlin.
❓ Predict Output
advanced
2:00remaining
Output of generic class with nullable type
What is the output of this Kotlin code using a generic class with a nullable type parameter?
Kotlin
class Wrapper<T>(val value: T?) {
    fun isNull(): Boolean = value == null
}

fun main() {
    val w = Wrapper<String>(null)
    println(w.isNull())
}
Atrue
Bfalse
CCompilation error due to null value
DNullPointerException at runtime
Attempts:
2 left
💡 Hint
Check how the nullable type is handled in the class.
🔧 Debug
expert
3:00remaining
Identify the error in this generic class declaration
What error does this Kotlin code produce?
Kotlin
class Pair<T, U>(val first: T, val second: U) {
    fun swap(): Pair<U, T> {
        return Pair(second, first)
    }
}

fun main() {
    val p = Pair(1, "one")
    val swapped = p.swap()
    println("${swapped.first}, ${swapped.second}")
}
ACompilation error: unresolved reference to Pair in swap()
BOutput: one, 1
CRuntime error: StackOverflowError
DCompilation error: recursive call in constructor
Attempts:
2 left
💡 Hint
Constructor calls using the class name are valid inside class methods in Kotlin.

Practice

(1/5)
1. What is the purpose of declaring a generic class in Kotlin using <T>?
easy
A. To restrict the class to only work with integers
B. To allow the class to work with any data type without rewriting code
C. To make the class abstract
D. To create a singleton class

Solution

  1. Step 1: Understand generic class declaration

    Declaring a generic class with <T> means the class can accept any type as a parameter.
  2. Step 2: Identify the benefit

    This allows the class to be flexible and reusable for different data types without rewriting the code.
  3. Final Answer:

    To allow the class to work with any data type without rewriting code -> Option B
  4. Quick Check:

    Generics = Flexible types [OK]
Hint: Generics mean 'any type' for flexible classes [OK]
Common Mistakes:
  • Thinking generics restrict types instead of generalizing
  • Confusing generics with abstract classes
  • Assuming generics create singletons
2. Which of the following is the correct syntax to declare a generic class named Box in Kotlin?
easy
A. class Box<T>;
B. class Box[T] { }
C. class Box<T> { }
D. class Box {<T>}

Solution

  1. Step 1: Recall Kotlin generic syntax

    Kotlin uses angle brackets <> to declare generics after the class name.
  2. Step 2: Check each option

    Only class Box<T> { } is correct, using angle brackets after the class name. The other options use semicolon after <T>, square brackets, or place <T> inside the braces.
  3. Final Answer:

    class Box<T> { } -> Option C
  4. Quick Check:

    Generics use <> brackets [OK]
Hint: Use angle brackets <T> after class name for generics [OK]
Common Mistakes:
  • Using square brackets [] instead of angle brackets
  • Adding semicolon after class declaration
  • Placing <T> inside curly braces
3. What will be the output of the following Kotlin code?
class Box<T>(val value: T) {
    fun getValue(): T = value
}

fun main() {
    val intBox = Box(123)
    val strBox = Box("Hello")
    println(intBox.getValue())
    println(strBox.getValue())
}
medium
A. 123\nHello
B. Box@123\nBox@Hello
C. Error: Type mismatch
D. null\nnull

Solution

  1. Step 1: Understand generic class usage

    The class Box holds a value of any type and returns it via getValue().
  2. Step 2: Trace the main function

    Two instances are created: one with an integer 123 and one with a string "Hello". Calling getValue() returns these values.
  3. Final Answer:

    123 Hello -> Option A
  4. Quick Check:

    Generic class returns stored value [OK]
Hint: Generic class returns stored value as is [OK]
Common Mistakes:
  • Expecting object reference output instead of value
  • Confusing type inference causing errors
  • Assuming null is returned
4. Identify the error in the following Kotlin generic class declaration:
class Container<T> {
    var item: T
    constructor(item: T) {
        this.item = item
    }
}
medium
A. No error, code is correct
B. Constructor syntax is incorrect
C. Generic type T is not declared properly
D. Property 'item' must be initialized or be abstract

Solution

  1. Step 1: Check property initialization

    The property item is declared but not initialized and not marked as abstract or lateinit.
  2. Step 2: Understand Kotlin property rules

    In Kotlin, non-null properties must be initialized or declared abstract/lateinit. Here, item is neither initialized nor marked, causing a compile error.
  3. Final Answer:

    Property 'item' must be initialized or be abstract -> Option D
  4. Quick Check:

    Uninitialized property causes error [OK]
Hint: Initialize properties or mark lateinit/abstract [OK]
Common Mistakes:
  • Forgetting to initialize properties
  • Misunderstanding constructor syntax
  • Thinking generic declaration is wrong
5. You want to create a generic class PairBox that holds two values of possibly different types. Which is the correct declaration for this class in Kotlin?
hard
A. class PairBox(val first: T, val second: U)
B. class PairBox<T>(val first: T, val second: T)
C. class PairBox { val first: T; val second: T }
D. class PairBox(val first: Any, val second: Any)

Solution

  1. Step 1: Understand requirement for two different types

    The class should accept two generic types, so it needs two type parameters, e.g., T and U.
  2. Step 2: Check each option

    class PairBox(val first: T, val second: U) correctly declares two generic types and constructor parameters. class PairBox<T>(val first: T, val second: T) uses one type for both values, not allowing different types. class PairBox { val first: T; val second: T } has wrong property types (second is T, should be U). class PairBox(val first: Any, val second: Any) uses Any which is not generic.
  3. Final Answer:

    class PairBox<T, U>(val first: T, val second: U) -> Option A
  4. Quick Check:

    Two generics for two types [OK]
Hint: Use two type parameters for different types [OK]
Common Mistakes:
  • Using one generic type for both values
  • Confusing property types in class body
  • Using Any instead of generics
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