Enums in Kotlin
1. What is an Enum in Kotlin?
An enum class in Kotlin is a special type that represents a set of constant values.
2. How do you declare an Enum in Kotlin?
Kotlin
Copied
3. Can enums have properties and methods?
Yes, enums can have properties and methods.
Kotlin
Copied
4. How are enum constants accessed in Kotlin?
Enum constants are accessed using their names.
Kotlin
Copied
5. Can enums have custom properties for each constant?
Yes, enums can have custom properties for each constant, as shown in the previous example.
6. What is the purpose of the values()
function in enums?
The values()
function returns an array of enum constants, allowing you to iterate over them.
Kotlin
Copied
7. How can you use enums in when expressions?
Enums are often used in when
expressions for exhaustive checks.
Kotlin
Copied
8. Can enums implement interfaces in Kotlin?
Yes, enums can implement interfaces.
Kotlin
Copied
9. What is the use of the valueOf()
function in enums?
The valueOf()
function is used to obtain an enum constant by its name.
Kotlin
Copied
10. How do you define custom methods for individual enum constants?
Custom methods are defined inside the enum class, as shown in a previous example.
11. Can enums have constructor parameters?
Yes, enums can have constructor parameters for each constant.
Kotlin
Copied
12. How do you get the ordinal value of an enum constant?
The ordinal value represents the position of an enum constant in the declaration order.
Kotlin
Copied
13. What is the purpose of the name
property in enums?
The name
property returns the name of the enum constant as a string.
Kotlin
Copied
14. How can you use enums in a when expression with multiple conditions?
Enums can be used in a when
expression with multiple conditions.
Kotlin
Copied
15. What is the significance of the compareTo()
function in enums?
The compareTo()
function is used to compare the ordinal values of two enum constants.
Kotlin
Copied
16. How can you iterate over the constants of an enum using a loop?
Enums can be iterated using a loop or using the values()
function.
Kotlin
Copied
17. How do you use enums for singleton pattern in Kotlin?
Enums can be used for implementing a singleton pattern in Kotlin.
Kotlin
Copied
18. What is the difference between an enum class and a regular class with constants?
Enum classes provide a more structured way to represent a fixed set of constants, and they can have behavior.
19. How can you use enum classes in a sealed class hierarchy?
Kotlin
Copied
20. How can you compare enum values in Kotlin?
Kotlin
Copied