0
0
Kotlinprogramming~5 mins

Generic class declaration in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a generic class in Kotlin?
A generic class in Kotlin is a class that can work with any data type. It uses a placeholder type parameter, allowing the class to be flexible and reusable with different types.
Click to reveal answer
beginner
How do you declare a generic class in Kotlin?
You declare a generic class by adding a type parameter inside angle brackets after the class name. For example: <br><code>class Box<T>(val value: T)</code> declares a generic class named Box with a type parameter T.
Click to reveal answer
beginner
What does the type parameter <code>T</code> represent in <code>class Box<T></code>?
The type parameter <code>T</code> is a placeholder for any type that will be specified when creating an instance of the class. It allows the class to hold or work with values of that type.
Click to reveal answer
beginner
Can you create an instance of a generic class with a specific type? Give an example.
Yes. For example, val intBox = Box<Int>(123) creates an instance of Box that holds an Int value 123. The type Int replaces the generic type parameter T.
Click to reveal answer
beginner
Why use generic classes instead of regular classes?
Generic classes let you write code once and use it with many types. This avoids repeating similar classes for each type and helps keep code clean and flexible.
Click to reveal answer
How do you declare a generic class named Container with a type parameter T in Kotlin?
Aclass Container<T>
Bclass Container(T)
Cclass Container<T>()
Dclass Container[]
What does the type parameter in a generic class represent?
AA fixed type like Int or String
BA variable name
CA function inside the class
DA placeholder for any type specified when creating an instance
Which of these is a valid way to create an instance of a generic class Box with type String?
Aval box = Box<String>("hello")
Bval box = Box(hello)
Cval box = Box<String>
Dval box = Box<String>(123)
Why are generic classes useful?
AThey replace functions
BThey make code slower
CThey allow code reuse with different types
DThey only work with Int types
What symbol is used to declare a type parameter in a Kotlin generic class?
A[ ]
B< >
C( )
D{ }
Explain how to declare a generic class in Kotlin and why it is useful.
Think about how you can write one class to work with many types.
You got /4 concepts.
    Describe how you create an instance of a generic class with a specific type and give an example.
    Remember to specify the type inside angle brackets when creating the object.
    You got /3 concepts.