What if your program could catch type mistakes before it even runs?
Why generics provide type safety in Kotlin - The Real Reasons
Imagine you have a box where you want to keep only apples. Without a clear rule, you might accidentally put oranges or bananas in it. When you open the box expecting apples, you might get surprised or confused.
Manually checking every item before putting it in the box is slow and easy to forget. Mistakes happen, and you might mix fruits. This causes problems later when you try to use the items assuming they are all apples.
Generics act like a smart label on the box that says "Only apples allowed." The compiler checks this for you, so you can never put the wrong fruit inside. This keeps your code safe and clear.
val box = mutableListOf<Any>() box.add("Apple") box.add(123) // Oops, wrong type!
val box = mutableListOf<String>() box.add("Apple") // box.add(123) // Error: Type mismatch
It lets you write safer code that catches mistakes early, so your program runs smoothly without unexpected errors.
Think of a grocery app that stores lists of fruits. Using generics ensures the list only holds fruit names, preventing bugs when showing or processing the list.
Manual checks are slow and error-prone.
Generics enforce rules automatically at compile time.
This leads to safer and clearer code.