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 lets you write Kotlin code and compile it to see the output on the same page.
Open the starter folder from the course material. You’ll see a Kotlin file with some code to get you started with this lesson. Here’s the code:
data class FruitBox<A, B, C, D>(
val firstItem: A,
val secondItem: B,
val numOfItems: C,
val totalCost: D
)
fun main() {
}
You’ll need to update the main() function with the following code:
val appleBananaBox = FruitBox("Apple", "Banana", 5, 10.5)
println(appleBananaBox)
The code above creates an instance of the FruitBox class called appleBananaBox, which will be initialized with four values. Those values will displayed on the console using the println.
Run the code above, and you’ll see the following message appear in the console:
FruitBox(firstItem=Apple, secondItem=Banana, numOfItems=5, totalCost=10.5)
You’ve got all the code working so far, but you haven’t used any data class features yet. Update the main() function with the following code:
val modifiedBox = appleBananaBox.copy(numOfItems = 7)
println("Modified Box: $modifiedBox")
Here’s a code breakdown:
You’ve used one of the data classes feature called copy() to copy the data of the appleBananaBox and modify the numOfItems value from 5 –> 7. Finally, you display the result using println.
Run the code to see the output to the console.