0
0
Kotlinprogramming~15 mins

Generic class declaration in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
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 T
Add a property called item of type T to the class
Create a variable intBox of type Box<Int> holding the number 123
Create 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
1
Create the generic class
Create a generic class called Box with one type parameter T. Inside the class, add a property called item of type T. Use a primary constructor to set item.
Kotlin
Need a hint?

Use class Box<T>(val item: T) to declare the generic class.

2
Create an integer box
Create a variable called intBox of type Box<Int> and set it to hold the number 123.
Kotlin
Need a hint?

Write val intBox: Box<Int> = Box(123) to create the integer box.

3
Create a string box
Create a variable called stringBox of type Box<String> and set it to hold the text "Hello".
Kotlin
Need a hint?

Write val stringBox: Box<String> = Box("Hello") to create the string box.

4
Print the box contents
Print the contents of intBox and stringBox using println. Print intBox.item first, then stringBox.item.
Kotlin
Need a hint?

Use println(intBox.item) and println(stringBox.item) to show the contents.