Understanding Enums in Kotlin
Understanding Enumerations
Welcome! Before we dive into Object-Oriented Programming, this lesson will introduce you to enumerations, commonly known as enums. You may have seen enums used to represent a fixed set of constants, such as the days of the week or directions (NORTH, SOUTH, EAST, WEST). In this lesson, we'll explore how to define and utilize enums, setting the foundation for future topics, including design patterns.
What You'll Learn
In this lesson, you'll learn how to create and use enumerations in Kotlin. We will:
- Define an enumeration to represent a collection of constants.
- Implement constructors and methods within an
enum. - Use enumerations in your code to access constants and methods.
Using the Planet example, you'll understand how enumerations can simplify coding logic and enhance code readability.
Defining the Enumeration
An enum in Kotlin is a special data type that allows a variable to be one of a set of predefined constants. In the Planet enum, each constant represents a distinct planet and is instantiated with specific mass and radius values. This ensures that the set of possible values for Planet is fixed and known at compile time.
Each constant (MERCURY, VENUS, etc.) is an instance of the Planet enum, initialized with specific mass and radius.
Constructor and Fields
Enums in Kotlin can also have fields, methods, and constructors. Below is the Planet enum with properties used to store the mass and radius of each planet:
These properties are declared as private val, meaning they are immutable once initialized and only accessible within the enum. This immutability is crucial because it ensures that the values associated with each constant do not change after they are set, preserving the integrity and consistency of the constants throughout the application's lifecycle.
