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.
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.
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.
Kotlin1enum class Planet(private val mass: Double, private val radius: Double) { 2 MERCURY(3.303e+23, 2.4397e6), 3 VENUS(4.869e+24, 6.0518e6), 4 EARTH(5.976e+24, 6.37814e6), 5 MARS(6.421e+23, 3.3972e6), 6 JUPITER(1.9e+27, 7.1492e7), 7 SATURN(5.688e+26, 6.0268e7), 8 URANUS(8.686e+25, 2.5559e7), 9 NEPTUNE(1.024e+26, 2.4746e7); 10}
Each constant (MERCURY
, VENUS
, etc.) is an instance of the Planet
enum, initialized with specific mass and radius.
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:
Kotlin1enum class Planet(private val mass: Double, private val radius: Double) { 2 MERCURY(3.303e+23, 2.4397e6), 3 VENUS(4.869e+24, 6.0518e6), 4 EARTH(5.976e+24, 6.37814e6), 5 MARS(6.421e+23, 3.3972e6), 6 JUPITER(1.9e+27, 7.1492e7), 7 SATURN(5.688e+26, 6.0268e7), 8 URANUS(8.686e+25, 2.5559e7), 9 NEPTUNE(1.024e+26, 2.4746e7); 10}
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.
The Planet
enum includes methods that provide functionality typical for a class. For example, methods to return the mass and radius values are defined as follows:
Kotlin1fun getMass(): Double { 2 return mass 3} 4 5fun getRadius(): Double { 6 return radius 7}
This demonstrates that enums
can not only act as fixed sets of constants but also encapsulate data and behavior associated with each constant.
Enums can also have additional methods to perform operations. The surfaceGravity
method within the Planet
enum calculates a planet's surface gravity using its mass and radius:
Kotlin1fun surfaceGravity(): Double { 2 val G = 6.67300E-11 // gravitational constant in m^3 kg^-1 s^-2 3 return G * mass / (radius * radius) 4}
Here, the method utilizes the unified gravitational constant G
and the instance variables mass
and radius
to compute gravity.
The surfaceWeight
method calculates how much an object would weigh on the planet:
Kotlin1fun surfaceWeight(otherMass: Double): Double { 2 return otherMass * surfaceGravity() 3}
The surfaceWeight
method calls surfaceGravity()
and multiplies it by the object's mass (otherMass
). This illustrates how enums
can encapsulate detailed behaviors and calculations related to their constants.
Here is the final, complete Planet
enum that we've developed throughout the lesson:
Kotlin1enum class Planet(private val mass: Double, private val radius: Double) { 2 MERCURY(3.303e+23, 2.4397e6), 3 VENUS(4.869e+24, 6.0518e6), 4 EARTH(5.976e+24, 6.37814e6), 5 MARS(6.421e+23, 3.3972e6), 6 JUPITER(1.9e+27, 7.1492e7), 7 SATURN(5.688e+26, 6.0268e7), 8 URANUS(8.686e+25, 2.5559e7), 9 NEPTUNE(1.024e+26, 2.4746e7); 10 11 fun getMass(): Double { 12 return mass 13 } 14 15 fun getRadius(): Double { 16 return radius 17 } 18 19 fun surfaceGravity(): Double { 20 val G = 6.67300E-11 21 return G * mass / (radius * radius) 22 } 23 24 fun surfaceWeight(otherMass: Double): Double { 25 return otherMass * surfaceGravity() 26 } 27}
This Planet
enum encapsulates not just the basic attributes of each planet, such as mass and radius, but also includes methods to calculate surface gravity and surface weight, making it a robust tool for planetary calculations.
Now that we have the complete Planet
enum, let's see how it can be used in a practical context:
Kotlin1fun main() { 2 val earth = Planet.EARTH 3 println("The mass of $earth is ${earth.getMass()} kg.") 4 println("The radius of $earth is ${earth.getRadius()} meters.") 5}
In this example, we retrieve the EARTH
constant from the Planet
enum and use it to access its getMass()
and getRadius()
methods.
Output:
1The mass of EARTH is 5.976E24 kg. 2The radius of EARTH is 6378140.0 meters.
The output shows the mass and radius values for Earth, illustrating how enum constants can encapsulate attributes and provide methods for accessing them.
This demonstrates how to leverage the methods we've defined to obtain specific information about each planet, making your code both intuitive and powerful.
Enumerations in Kotlin are powerful because they bring several advantages:
- Type Safety: They ensure that variables of the enum type can only hold predefined values, helping to avoid errors related to invalid values.
- Code Readability: Enumerations improve readability by grouping related constants and their associated behaviors in a cohesive manner, making the code easier to understand.
- Maintainability: By encapsulating related constants and their behaviors,
enums
help keep the code maintainable. Changes and updates are easier to manage within a well-defined structure.
Using the Planet
enum example, we can see these advantages in action. Enums are used not just to define constants (like the mass and radius of planets) but also to associate detailed data and behavior (such as calculating surface gravity and weight) with those constants. This leads to cleaner and more maintainable code, demonstrating how enums
can transform the way you write and organize your Kotlin programs.
Ready? Let's jump into the practice section and see how enumerations can transform your code!