How to resolve the algorithm Enumerations step by step in the Kotlin programming language

Published on 22 June 2024 08:30 PM

How to resolve the algorithm Enumerations step by step in the Kotlin programming language

Table of Contents

Problem Statement

Create an enumeration of constants with and without explicit values.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Enumerations step by step in the Kotlin programming language

The code you provided is a Kotlin program that defines two enums and then prints the values and ordinals of each enum.

An enum is a type that represents a fixed set of values. In Kotlin, enums are declared using the enum class keyword.

The first enum, Animals, defines three values: CAT, DOG, and ZEBRA. The second enum, Dogs, defines three values: BULLDOG, TERRIER, and WOLFHOUND, each of which has an associated ID.

The main() function is the entry point of the program. The first for loop iterates over the values of the Animals enum and prints the name and ordinal of each value. The second for loop iterates over the values of the Dogs enum and prints the name and ID of each value.

The output of the program is:

CAT     : 0
DOG     : 1
ZEBRA   : 2

BULLDOG   : 1
TERRIER   : 2
WOLFHOUND : 4

Source code in the kotlin programming language

// version 1.0.5-2

enum class Animals {
    CAT, DOG, ZEBRA
}

enum class Dogs(val id: Int) {
    BULLDOG(1), TERRIER(2), WOLFHOUND(4)
}

fun main(args: Array<String>) {
    for (value in Animals.values()) println("${value.name.padEnd(5)} : ${value.ordinal}")
    println()
    for (value in Dogs.values()) println("${value.name.padEnd(9)} : ${value.id}")
}


  

You may also check:How to resolve the algorithm Integer comparison step by step in the Fortran programming language
You may also check:How to resolve the algorithm Return multiple values step by step in the Factor programming language
You may also check:How to resolve the algorithm Zero to the zero power step by step in the Pike programming language
You may also check:How to resolve the algorithm Sorting algorithms/Insertion sort step by step in the Elixir programming language
You may also check:How to resolve the algorithm Parse an IP Address step by step in the Java programming language