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.
First, create an enum class called FruitType:
enum class FruitType {
APPLE,
BANANA,
ORANGE,
GRAPE
}
This enum class has four fruit types: Apple, Banana, Orange, and Grape.
Next, you’ll create a standard class called FruitBox:
class FruitBox(
val firstItem: String,
val secondItem: String,
val numOfItems: Int,
val totalCost: Double,
val fruitType: FruitType
)
This class has five variables. You can see there’s a variable called fruitType of a type FruitType. You’ll use this to access the values inside the FruitType enum class.
Now, create a new function inside the FruitBox class called printContents():
fun printContents() {
println("FruitBox contents: First Item = $firstItem, Second Item = $secondItem")
println("Total Items = $numOfItems, Total Cost = $$totalCost")
println("Fruit Type: $fruitType")
}
This function prints some values to the console. Next, update the main() function to display the values.
val appleBananaBox = FruitBox("Apple", "Banana", 5, 10.5, FruitType.APPLE)
appleBananaBox.printContents()
Here’s a code breakdown:
-
You declare a variable named
appleBananaBoxand initialize it with a new instance of theFruitBoxclass. -
The
FruitBoxclass takes five parameters in its constructor, and one of them is the enum typefruitType.This shows how you can call the enum class values and pass them through theprintContents(). -
Finally, call
printContents()to display all the values to the console.
Run the code to see the output to the console.