How to convert enum to string in Scala?

Scala | Convert enum to string: Here, we are going to learn a method to convert given enum to string in Scala.
Submitted by Shivang Yadav, on June 13, 2020

Before learning about the conversion let's discuss for basics about enum and strings.

enum is also known as Enumeration is a set of named constants that are used in modeling in programming languages.

Example:

object programming_language extends Enumerations {
    val c, c++, scala, java, javascript, python = Value
}

String in Scala is a collection of characters. It is a mutable object i.e. once created the string values cannot be changed.

Example:

val string : String = "includehelp.com"

Convert enum to string

We can convert an enum object to string in Scala. For this, we have to provide a string value to all the named constants which will be then printed. The conversion will be done using the toString() method present in the Scala library.

Syntax:

enum_object.value.toString

Scala program to convert enum to string

// Program to convert enum to string in Scala
object MyClass {
    // Creating a Enum
    object programmingLang extends Enumeration {
        val C = Value("C programming language")
        val java = Value("Java programming language")
        val scala = Value("Scala programming language")
        val javascript = Value("JavaScript programming language.")
    }
    def main(args: Array[String]) {
        // Converting to String
        println("The string conversion of each value of Enum is :")
        println(programmingLang.C.toString)
        println(programmingLang.java.toString)
        println(programmingLang.scala.toString)
        println(programmingLang.javascript.toString)
    }
}

Output:

The string conversion of each value of Enum is :
C programming language
Java programming language
Scala programming language
JavaScript programming language.

Description:

In the above code we have created an enumeration named programmingLang with 4 values and then using the tostring method we have converted enum value to string which is printed to output using println() method.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.