📖 Scenario: Imagine you are organizing a library where you want to keep track of books by their titles. You want to make sure that only book titles (strings) are stored in your list to avoid confusion.
🎯 Goal: You will create a list that only accepts strings using generics in Kotlin. This will help you understand how generics provide type safety by preventing wrong data types from being added.
📋 What You'll Learn
Create a list of strings using Kotlin generics
Add some book titles to the list
Try to add a number to the list (commented out to avoid error)
Print the list to see the stored book titles
💡 Why This Matters
🌍 Real World
Using generics helps avoid bugs in apps by making sure data is the right type, like keeping only book titles in a list of books.
💼 Career
Understanding generics and type safety is important for writing clean, error-free Kotlin code in professional Android or backend development.
Progress0 / 4 steps
1
Create a list of book titles
Create a variable called bookTitles that is a mutable list of strings using Kotlin generics.
Kotlin
Hint
Use MutableList<String> to specify a list that only holds strings.
2
Add book titles to the list
Add the strings "Kotlin Basics" and "Advanced Kotlin" to the bookTitles list using the add method.
Kotlin
Hint
Use bookTitles.add("Your Title") to add each book title.
3
Try to add a number to the list (type safety)
Add a commented out line that tries to add the number 123 to the bookTitles list to show that Kotlin prevents adding wrong types.
Kotlin
Hint
Comment out the line with // to show it causes an error if uncommented.
4
Print the list of book titles
Print the bookTitles list using println to show the stored book titles.
Kotlin
Hint
Use println(bookTitles) to display the list.
Practice
(1/5)
1. Why do generics in Kotlin help provide type safety?
easy
A. They automatically convert types at runtime.
B. They allow any type without restrictions.
C. They make the program run faster.
D. They check types at compile time to prevent errors.
Solution
Step 1: Understand generics role in type checking
Generics allow specifying the type a class or function works with, so the compiler can check if the correct type is used.
Step 2: Identify how this prevents errors
By checking types early, generics prevent mixing incompatible types, avoiding bugs before running the program.
Final Answer:
They check types at compile time to prevent errors. -> Option D
Quick Check:
Generics = Compile-time type checks [OK]
Hint: Generics catch wrong types before running code [OK]
Common Mistakes:
Thinking generics allow any type without checks
Believing generics speed up runtime
Confusing compile-time and runtime type checks
2. Which of the following is the correct syntax to declare a generic class in Kotlin?
easy
A. class Box { var value: T }
B. class Box<T> { var value: T }
C. class Box<T> { var value: Int }
D. class Box<T> (value: T) : T
Solution
Step 1: Review generic class syntax
In Kotlin, generic classes declare a type parameter inside angle brackets after the class name, like class Box<T>.
Step 2: Check property type usage
The property inside should use the generic type T, not a fixed type like Int.
Final Answer:
class Box<T> { var value: T } -> Option B
Quick Check:
Generic class syntax = class Box<T> { var value: T } [OK]
Hint: Generic type goes in angle brackets after class name [OK]
Common Mistakes:
Using fixed types instead of generic type parameter
Omitting the generic type parameter declaration
Incorrect inheritance syntax with generics
3. What will be the output of this Kotlin code?
fun main() {
val list: List<String> = listOf("apple", "banana")
val first: String = list[0]
println(first.length)
}
medium
A. Syntax error
B. Runtime error
C. 5
D. 0
Solution
Step 1: Understand the list type and access
The list is declared as List<String>, so it only holds strings. Accessing list[0] returns "apple".
Step 2: Calculate the length of the first string
"apple" has 5 characters, so first.length is 5, which is printed.
Final Answer:
5 -> Option C
Quick Check:
"apple" length = 5 [OK]
Hint: Check type and value before output [OK]
Common Mistakes:
Confusing list element type causing errors
Expecting runtime error due to generics
Miscounting string length
4. Identify the error in this Kotlin code using generics:
fun printFirst(list: List<Int>) {
val first = list[0]
println(first.length)
}
medium
A. Cannot call length on Int type
B. List<Int> cannot be indexed
C. Missing generic type declaration
D. Function return type is missing
Solution
Step 1: Analyze the list element type
The list holds Int values, so first is an integer.
Step 2: Check the method called on the element
Calling length on an integer is invalid because Int does not have a length property.
Final Answer:
Cannot call length on Int type -> Option A
Quick Check:
Int has no length property [OK]
Hint: Check methods valid for the generic type used [OK]
Common Mistakes:
Assuming all types have length property
Thinking indexing List<Int> is invalid
Ignoring type mismatch errors
5. How do generics prevent mixing wrong types in Kotlin collections? Consider this code:
val numbers: MutableList<Number> = mutableListOf(1, 2.5, 3)
numbers.add(4.0f)
numbers.add("five")
What happens and why?
hard
A. Compilation error on adding "five" because it's not a Number
B. All values added successfully, no errors
C. Runtime error when adding 4.0f
D. Compilation error on adding 4.0f because it's a Float
Solution
Step 1: Understand the collection type
The list is declared as MutableList<Number>, so it accepts any subtype of Number like Int, Double, Float.
Step 2: Check the added elements
Adding 4.0f (a Float) is allowed because Float is a Number subtype. Adding "five" (a String) causes a compile-time error because String is not a Number.
Final Answer:
Compilation error on adding "five" because it's not a Number -> Option A
Quick Check:
Generics block wrong types at compile time [OK]
Hint: Only add types matching generic parameter [OK]
Common Mistakes:
Thinking all types can be added to Number list
Confusing runtime and compile-time errors
Assuming Float is not a Number subtype
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.