Advanced Kotlin Class Features

May 22 2024 · Kotlin 1.9, Android 14, Android Studio Hedgehog

Lesson 06: Leverage Enum Classes

Demo

Episode complete

Play next episode

Next
Transcript

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:

  1. You declare a variable named appleBananaBox and initialize it with a new instance of the FruitBox class.
  2. The FruitBox class takes five parameters in its constructor, and one of them is the enum type fruitType. This shows how you can call the enum class values and pass them through the printContents().
  3. Finally, call printContents() to display all the values to the console.

Run the code to see the output to the console.

See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion