0
0
Kotlinprogramming~15 mins

Multiple type parameters in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Multiple Type Parameters in Kotlin
📖 Scenario: Imagine you are building a simple app to store pairs of related information, like a person's name and their age, or a product and its price.
🎯 Goal: You will create a generic class in Kotlin that uses two type parameters to hold pairs of values of different types. Then, you will create an instance of this class and print its contents.
📋 What You'll Learn
Create a generic class called PairBox with two type parameters: A and B
Add two properties to PairBox: first of type A and second of type B
Create a variable called person that is an instance of PairBox holding a String and an Int
Print the values of person.first and person.second in a friendly sentence
💡 Why This Matters
🌍 Real World
Generic classes with multiple type parameters are useful when you want to store or work with pairs or groups of related data of different types, like key-value pairs or coordinate points.
💼 Career
Understanding generics and multiple type parameters is important for writing reusable and type-safe code in Kotlin, which is widely used in Android app development and backend services.
Progress0 / 4 steps
1
Create the generic class with two type parameters
Create a generic class called PairBox with two type parameters A and B. Inside the class, declare two properties: first of type A and second of type B.
Kotlin
Need a hint?

Use the syntax class PairBox(val first: A, val second: B) to define the class.

2
Create an instance of PairBox
Create a variable called person and assign it an instance of PairBox with String and Int as type arguments. Use the values "Alice" for first and 30 for second.
Kotlin
Need a hint?

Use val person = PairBox("Alice", 30) to create the instance.

3
Access the properties of the PairBox instance
Write a variable called description that uses string interpolation to create a sentence: "Name: person.first, Age: person.second".
Kotlin
Need a hint?

Use val description = "Name: ${person.first}, Age: ${person.second}" to create the sentence.

4
Print the description
Write a println statement to print the variable description.
Kotlin
Need a hint?

Use println(description) to show the sentence on the screen.