0
0
Kotlinprogramming~30 mins

Enum with properties and methods in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Enum with properties and methods
📖 Scenario: Imagine you are creating a simple app that shows different types of coffee sizes with their prices and descriptions.
🎯 Goal: You will create an enum class in Kotlin that has properties and a method to describe each coffee size.
📋 What You'll Learn
Create an enum class called CoffeeSize with three entries: SMALL, MEDIUM, and LARGE
Each enum entry should have two properties: price (Double) and description (String)
Add a method called displayInfo() inside the enum that returns a string combining the size name, price, and description
Print the result of calling displayInfo() on each enum entry
💡 Why This Matters
🌍 Real World
Enums with properties and methods are useful to represent fixed sets of related data with extra details, like product sizes, statuses, or categories.
💼 Career
Understanding enums with properties and methods helps in writing clean, organized code in Kotlin, which is valuable for Android development and backend services.
Progress0 / 4 steps
1
Create the enum class with entries and properties
Create an enum class called CoffeeSize with three entries: SMALL, MEDIUM, and LARGE. Each entry should have two properties: price of type Double and description of type String. Use the exact values: SMALL(2.5, "Small cup"), MEDIUM(3.5, "Medium cup"), LARGE(4.5, "Large cup").
Kotlin
Need a hint?

Remember to declare the properties inside the parentheses after the enum name and separate entries with commas.

2
Add a method to display info
Inside the CoffeeSize enum class, add a method called displayInfo() that returns a String. This method should return a string in the format: "Size: [name], Price: $[price], Description: [description]". Use the enum's name property for the size name.
Kotlin
Need a hint?

Use the name property of the enum to get the size name. Use string templates with $ to insert values.

3
Call the method for each enum entry
Write a main function. Inside it, use a for loop with variable size to iterate over CoffeeSize.values(). For each size, call displayInfo() and store the results in a list called infoList.
Kotlin
Need a hint?

Use CoffeeSize.values() to get all enum entries. Add each displayInfo() result to infoList.

4
Print the info list
In the main function, after the loop, print each string in infoList on its own line using a for loop with variable info.
Kotlin
Need a hint?

Use println(info) inside the loop to print each string on its own line.