Open your internet browser and search for Kotlin Playground. You’ll see different websites. Select the one provided by the Android Developers page. This web-based compiler allows you to write Kotlin code and compile it to see the output on the same page.
First, define a class called FruitBox
. This class has four variables with different data types:
class FruitBox<A, B, C : Number, D : Number>(
private val firstItem: A,
private val secondItem: B,
private val numOfItems: C,
private val totalCost: D
) {
}
Here’s a code breakdown:
-
class FruitBox<A, B, C : Number, D : Number>
declares a generic class namedFruitBox
with four type parameters: A, B, C, and D. -
private val firstItem: A and private val secondItem: B
: These two private variables store the two items in theFruitBox
, each of generic types A and B. -
private val numOfItems: C
is a private variable representing the number of items in theFruitBox
. TypeC
is constrained to be a subtype of a Number. -
private val totalCost: D
is another private variable representing the total cost of the items in theFruitBox
. TypeD
is constrained to be a subtype of Number.
Now that you’ve declared the variables you need, declare a generic function within the FruitBox
to print the output of those variables to the console.
Create a new function called printContents
with the following code:
fun <A, B, C : Number, D : Number> printContents(fruitBox: FruitBox<A, B, C, D>) {
println("FruitBox contents: First Item = ${fruitBox.firstItem}, Second Item = ${fruitBox.secondItem}")
println("Total Items = ${fruitBox.numOfItems}, Total Cost = $${fruitBox.totalCost}")
}
Here’s a code breakdown:
-
<A, B, C : Number, D : Number>
are the generic type parameters for the function. They help you specify different types for the properties of theFruitBox
instance passed to the function. -
A
andB
are generic types for the first and second items in theFruitBox
, whileC
andD
are generic types constrained to be subclasses ofNumber
, used for the number of items and total cost in theFruitBox
. -
FruitBox<A, B, C, D>
specifies the parameterFruitBox
. You use theprintln
statements to display the details about the first and second items, the total number of items, and the cost.
Running the code right now won’t display anything to the console because you haven’t yet called the printContents
function from the main
function. Create instances of the FruitBox
and use the printContents
in the main function to print the output to the console:
fun main() {
val appleBananaBox = FruitBox("Apple", "Banana", 5, 10.5)
appleBananaBox.printContents()
}
Here’s a breakdown of the code above:
-
val appleBananaBox = FruitBox("Apple", "Banana", 5, 10.5)
creates an instance ofFruitBox
with specific items,Apple
andBanana
, a quantity of 5, and a total cost of 10.5. -
appleBananaBox.printContents()
Prints out the content of the box to the console.
Now, run the code to see the output to the console.