0
0
Kotlinprogramming~5 mins

Enum entries iteration in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is an enum in Kotlin?
An enum in Kotlin is a special class that represents a group of constants. Each constant is called an enum entry.
Click to reveal answer
beginner
How do you get all entries of an enum in Kotlin?
You use the values() function, which returns an array of all enum entries.
Click to reveal answer
beginner
Write a Kotlin code snippet to print all entries of an enum named Color.
enum class Color { RED, GREEN, BLUE }

fun main() {
    for (color in Color.values()) {
        println(color)
    }
}
Click to reveal answer
beginner
Can you use a for loop to iterate over enum entries in Kotlin?
Yes, you can use a for loop with EnumClass.values() to go through each enum entry one by one.
Click to reveal answer
intermediate
What type does values() return when called on an enum class?
It returns an array of the enum type, for example, Array<Color> if called on Color enum.
Click to reveal answer
Which function returns all entries of an enum in Kotlin?
Aall()
Bentries()
Cvalues()
Dlist()
How do you iterate over enum entries in Kotlin?
AUsing a for loop with <code>EnumClass.values()</code>
BUsing <code>EnumClass.entries()</code>
CUsing a while loop with <code>EnumClass.all()</code>
DUsing <code>EnumClass.list()</code>
What type does EnumClass.values() return?
AArray of enum entries
BList of enum entries
CSet of enum entries
DMap of enum entries
Can you modify the array returned by values() to add new enum entries?
AYes, you can add new entries anytime
BNo, enum entries are fixed at compile time
CYes, but only inside the enum class
DOnly if you use a mutable list
What will this code print?
enum class Day { MON, TUE, WED }
fun main() {
  for (d in Day.values()) println(d)
}
A0 1 2
BError
CDay.MON Day.TUE Day.WED
DMON TUE WED
Explain how to iterate over all entries of an enum in Kotlin and why this is useful.
Think about how you can get all enum constants and loop through them.
You got /4 concepts.
    Describe what the values() function returns when called on an enum class and how you can use it.
    Consider the type and purpose of the <code>values()</code> function.
    You got /4 concepts.