CodeBlanks Logo Icon CodeBlanks

Enum properties

Learn to define properties and methods in enums.

Enum properties: constructor and field

An enum class can take a constructor and properties. Each constant is declared with a value that fits the constructor.

enum class Planet(val distance: Int) {
    MERCURY(57), VENUS(108), EARTH(150)
}
println(Planet.EARTH.distance)  // 150

Each constant takes a value in parentheses; the value binds to the distance property. This lets you attach meaningful data to constants. Data lives with the constant; no separate table is needed.

Methods inside an enum

You can define a method inside an enum class. The method can access the constant's properties.

enum class Planet(val distance: Int) {
    MERCURY(57), VENUS(108), EARTH(150);
    fun isClose() = distance < 100
}
println(Planet.EARTH.isClose())  // false

A semicolon goes after the constant list; then the method follows. Inside the method you access properties like distance directly. This way behaviour lives with the data.

Practice Add an emoji property to Mood

Define an enum class called Mood with a constructor property val emoji: String. Constants: HAPPY(":)"), SAD(":("). In main print the emoji value of the HAPPY constant.

Starter code

Main.kt
fun main() {
    // Define a mood type and print one constant's emoji
}

Sample solution

Main.kt
enum class Mood(val emoji: String) {
    HAPPY(":)"), SAD(":(")
}

fun main() {
    println(Mood.HAPPY.emoji)
}

Expected output

:)

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Fill in the blank: declare the property

Question
enum class Planet(val ____: Int) { MERCURY(57), VENUS(108) }
Answer
enum class Planet(val distance: Int) { MERCURY(57), VENUS(108) }

Explanation: val distance: Int comes with the constructor.

2 What does enum class Planet(val distance: Int) define?

  • An interface
  • Only a method
  • Only constants
  • A property and constructor Correct answer

Explanation: The distance property comes from the constructor parameter.

3 Match piece to role

Term Meaning
distance Planet property
MERCURY(57) Constructor call
isClose() Method
57 Value

4 Fill in the blank: call the method

Question
val p = Planet.EARTH
val close = p.____()
Answer
val p = Planet.EARTH
val close = p.isClose()

Explanation: you call the isClose() method.

All lessons in Beginner