Generic class declaration
📖 Scenario: Imagine you want to create a box that can hold any type of item, like a box for toys, books, or fruits. Instead of making a new box for each type, you can make one generic box that works for all.
🎯 Goal: You will create a generic class called Box that can hold one item of any type. Then, you will create a box for an Int and a box for a String, and finally print the contents.
📋 What You'll Learn
Create a generic class called
Box with one type parameter TAdd a property called
item of type T to the classCreate a variable
intBox of type Box<Int> holding the number 123Create a variable
stringBox of type Box<String> holding the text "Hello"Print the contents of
intBox and stringBox💡 Why This Matters
🌍 Real World
Generic classes let you write flexible code that works with many data types without repeating yourself. For example, collections like lists and maps use generics.
💼 Career
Understanding generics is important for Kotlin developers to write reusable and type-safe code, which is a common requirement in professional software development.
Progress0 / 4 steps