Enum Classes in Kotlin: A Beginner’s Guide with Examples

Enum Classes in Kotlin: A Beginner's Guide with Examples

In today’s tutorial, we learn about Enum classes in Kotlin, which are used for predefined constants. Using Enum classes, we can define a set of type-safe enums, and each enum represents an object. We can add multiple enums inside a single enum class separated by a comma. Enum is used to define a fixed set of constant values in Kotlin.

Enum Classes in Kotlin: A Beginner’s Guide with Examples

Define Enum classes in Kotlin:

We will use the enum keyword to declare an enum class in Koltin. To add multiple constants in the enum class each constant should be separated by a comma. You can also define properties and functions in the enum class.

Code example:

Code explanation:

We have created an Enum class Subjects and adding multiple subject as constants into the class. We can directly call the constant using ClassName + Dot operator + Constant name.

Code example 2:

Code explanation: In the above example, we added a custom function for each Enum and printed a short description of each subject. We can use these functions using emus later on.

Conclusion:

Enums are useful when we know the values we are going to use in our program or if they are Fixed for the whole application. So it’s completely up to us what type of values we want to make as Enums. They could be Navigation tab names, Color constants, etc. So keep practicing and you will master them, Happy coding.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *